code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
byte[] toByteArray(ByteArrayOutputStream os)
{
byte[] buf = device.toByteArray();
os.write(buf, 0, buf.length);
buf = suppfam.toByteArray();
os.write(buf, 0, buf.length);
if (mfr != null) {
buf = mfr.toByteArray();
os.write(buf, 0, buf.length);
}
return os.toByteArray();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray
(java.io.ByteArrayOutputStream) |
public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());
} | Builds a instance of the class for a map containing the values, without specifying the handler for differences
@param clazz The class to build instance
@param values The values map
@return The instance
@throws InstantiationException Error instantiating
@throws IllegalAccessException Access error
@throws IntrospectionException Introspection error
@throws IllegalArgumentException Argument invalid
@throws InvocationTargetException Invalid target |
public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
log.debug("Building new instance of Class " + clazz.getName());
T instance = clazz.newInstance();
for (String key : values.keySet()) {
Object value = values.get(key);
if (value == null) {
log.debug("Value for field " + key + " is null, so ignoring it...");
continue;
}
log.debug(
"Invoke setter for " + key + " (" + value.getClass() + " / " + value.toString() + ")");
Method setter = null;
try {
setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();
} catch (Exception e) {
throw new IllegalArgumentException("Setter for field " + key + " was not found", e);
}
Class<?> argumentType = setter.getParameterTypes()[0];
if (argumentType.isAssignableFrom(value.getClass())) {
setter.invoke(instance, value);
} else {
Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);
setter.invoke(instance, newValue);
}
}
return instance;
} | Builds a instance of the class for a map containing the values
@param clazz Class to build
@param values Values map
@param differenceHandler The difference handler
@return The created instance
@throws InstantiationException Error instantiating
@throws IllegalAccessException Access error
@throws IntrospectionException Introspection error
@throws IllegalArgumentException Argument invalid
@throws InvocationTargetException Invalid target |
public static <T extends Annotation> T getClosestAnnotation(Method method, Class<T> typeOfT) {
T annotation = method.getAnnotation(typeOfT);
if (annotation == null) {
Class<?> clazzToIntrospect = method.getDeclaringClass();
while (annotation == null && clazzToIntrospect != null) {
annotation = clazzToIntrospect.getAnnotation(typeOfT);
clazzToIntrospect = clazzToIntrospect.getSuperclass();
}
}
return annotation;
} | Get the closest annotation for a method (inherit from class)
@param method method
@param typeOfT type of annotation inspected
@return annotation instance |
protected EndpointInfo createEndpointInfo() throws BusException {
String transportId = getTransportId();
if (transportId == null && getAddress() != null) {
DestinationFactory df = getDestinationFactory();
if (df == null) {
DestinationFactoryManager dfm = getBus().getExtension(DestinationFactoryManager.class);
df = dfm.getDestinationFactoryForUri(getAddress());
}
if (df != null) {
transportId = df.getTransportIds().get(0);
}
}
// default to http transport
if (transportId == null) {
transportId = "http://schemas.xmlsoap.org/wsdl/soap/http";
}
setTransportId(transportId);
EndpointInfo ei = new EndpointInfo();
ei.setTransportId(transportId);
ei.setName(serviceFactory.getService().getName());
ei.setAddress(getAddress());
ei.setProperty(PROTOBUF_MESSAGE_CLASS, messageClass);
BindingInfo bindingInfo = createBindingInfo();
ei.setBinding(bindingInfo);
return ei;
} | /*
EndpointInfo contains information form WSDL's physical part such as endpoint address, binding, transport etc. For
JAX-RS based EndpointInfo, as there is no WSDL, these information are set manually, eg, default transport is
http, binding is JAX-RS binding, endpoint address is from server mainline. |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle Message Sensor Multi Level Request");
logger.debug(String.format(
"Received Sensor Multi Level Request for Node ID = %d", this
.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SENSOR_MULTI_LEVEL_GET:
case SENSOR_MULTI_LEVEL_SUPPORTED_GET:
case SENSOR_MULTI_LEVEL_SUPPORTED_REPORT:
logger.warn(String.format("Command 0x%02X not implemented.",
command));
return;
case SENSOR_MULTI_LEVEL_REPORT:
logger.trace("Process Multi Level Sensor Report");
logger.debug(String.format(
"Sensor Multi Level report from nodeId = %d", this
.getNode().getNodeId()));
// TODO: sensor type not used for anything currently
// TODO: should extend to support filtering of sensor results based on type
int sensorTypeCode = serialMessage.getMessagePayloadByte(offset + 1);
logger.debug(String.format("Sensor Type = (0x%02x)", sensorTypeCode));
byte[] valueData = Arrays.copyOfRange(
serialMessage.getMessagePayload(), offset + 2,
serialMessage.getMessagePayload().length);
BigDecimal value = extractValue(valueData);
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.SENSOR_EVENT,
this.getNode().getNodeId(), endpoint, value);
this.getController().notifyEventListeners(zEvent);
break;
default:
logger.warn(String
.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command, this.getCommandClass().getLabel(), this
.getCommandClass().getKey()));
}
} | {@inheritDoc} |
public static Priority get(int value)
{
if (value == 1)
return NORMAL;
if (value == 0)
return SYSTEM;
if (value == 3)
return LOW;
if (value == 2)
return URGENT;
throw new KNXIllegalArgumentException("invalid priority value");
} | Returns the priority of the supplied priority value code.
<p>
@param value priority value code, 0 <= value <= 3
@return the corresponding priority object |
public void add(Datapoint dp)
{
synchronized (points) {
if (points.containsKey(dp.getMainAddress()))
throw new KNXIllegalArgumentException("duplicate datapoint "
+ dp.getMainAddress());
points.put(dp.getMainAddress(), dp);
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.datapoint.DatapointModel#add
(tuwien.auto.calimero.datapoint.Datapoint) |
public void load(XMLReader r) throws KNXMLException
{
if (r.getPosition() != XMLReader.START_TAG)
r.read();
final Element e = r.getCurrent();
if (r.getPosition() != XMLReader.START_TAG || !e.getName().equals(TAG_DATAPOINTS))
throw new KNXMLException(TAG_DATAPOINTS + " element not found", e != null ? e
.getName() : null, r.getLineNumber());
synchronized (points) {
while (r.read() == XMLReader.START_TAG) {
final Datapoint dp = Datapoint.create(r);
if (points.containsKey(dp.getMainAddress()))
throw new KNXMLException(TAG_DATAPOINTS + " element contains "
+ "duplicate datapoint", dp.getMainAddress().toString(), r
.getLineNumber());
points.put(dp.getMainAddress(), dp);
}
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.datapoint.DatapointModel#load
(tuwien.auto.calimero.xml.XMLReader) |
public void save(XMLWriter w) throws KNXMLException
{
w.writeElement(TAG_DATAPOINTS, Collections.EMPTY_LIST, null);
synchronized (points) {
for (final Iterator i = points.values().iterator(); i.hasNext();)
((Datapoint) i.next()).save(w);
}
w.endElement();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.datapoint.DatapointModel#save
(tuwien.auto.calimero.xml.XMLWriter) |
public static Class<?> loadClassNew(BundleContext context, String klassName) throws ClassNotFoundException {
// extract package
String packageName = klassName.substring(0, klassName.lastIndexOf('.'));
BundleCapability exportedPackage = getExportedPackage(context, packageName);
if (exportedPackage == null) {
throw new ClassNotFoundException("No package found with name " + packageName + " while trying to load the class "
+ klassName + ".");
}
return exportedPackage.getRevision().getBundle().loadClass(klassName);
} | Load the Class of name <code>klassName</code>.
TODO : handle class version
@param context The BundleContext
@param klassName The Class name
@return The Class of name <code>klassName</code>
@throws ClassNotFoundException if we can't load the Class of name <code>klassName</code> |
private static BundleCapability getExportedPackage(BundleContext context, String packageName) {
List<BundleCapability> packages = new ArrayList<BundleCapability>();
for (Bundle bundle : context.getBundles()) {
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {
String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
if (pName.equalsIgnoreCase(packageName)) {
packages.add(packageCapability);
}
}
}
Version max = Version.emptyVersion;
BundleCapability maxVersion = null;
for (BundleCapability aPackage : packages) {
Version version = (Version) aPackage.getAttributes().get("version");
if (max.compareTo(version) <= 0) {
max = version;
maxVersion = aPackage;
}
}
return maxVersion;
} | Return the BundleCapability of a bundle exporting the package packageName.
@param context The BundleContext
@param packageName The package name
@return the BundleCapability of a bundle exporting the package packageName |
public static Class<?> loadClass(BundleContext context, String klassName) throws ClassNotFoundException {
ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
try {
PackageAdmin padmin = (PackageAdmin) context.getService(sref);
// extract package name
String packageName = klassName.substring(0, klassName.lastIndexOf('.'));
ExportedPackage pkg = padmin.getExportedPackage(packageName);
if (pkg == null) {
try {
return context.getBundle().loadClass(klassName);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("No package found with name " + packageName + " while trying to load the class "
+ klassName + ".", e);
}
}
return pkg.getExportingBundle().loadClass(klassName);
} finally {
context.ungetService(sref);
}
} | Load the Class of name <code>klassName</code>.
TODO : handle class version
@param context The BundleContext
@param klassName The Class name
@return The Class of name <code>klassName</code>
@throws ClassNotFoundException if we can't load the Class of name <code>klassName</code> |
public static List<Class<?>> loadClasses(BundleContext context, List<String> klassNames) throws ClassNotFoundException {
ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
List<Class<?>> klass = new ArrayList<Class<?>>(klassNames.size());
if (sref == null) {
// no package admin !
return klass;
}
try {
PackageAdmin padmin = (PackageAdmin) context.getService(sref);
for (String klassName : klassNames) {
// extract package name
String packageName = klassName.substring(0, klassName.lastIndexOf('.'));
ExportedPackage pkg = padmin.getExportedPackage(packageName);
if (pkg == null) {
throw new ClassNotFoundException("No package found with name " + packageName + " while trying to load the class "
+ klassName + ".");
}
klass.add(pkg.getExportingBundle().loadClass(klassName));
}
return klass;
} finally {
context.ungetService(sref);
}
} | Load the Classes of names <code>klassNames</code>.
TODO : handle class version
@param context The BundleContext
@param klassNames The Classes names
@return The Classes of names <code>klassNames</code>
@throws ClassNotFoundException if we can't load one Class name of the list <code>klassNames</code> |
public int read(byte[] b) throws IOException
{
if (b == null)
throw new NullPointerException();
return p.readBytes(b, 0, b.length);
} | /* (non-Javadoc)
@see java.io.InputStream#read(byte[]) |
public int read(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if (off < 0 || len < 0 || len > b.length - off)
throw new IndexOutOfBoundsException();
return p.readBytes(b, off, len);
} | /* (non-Javadoc)
@see java.io.InputStream#read(byte[], int, int) |
public InputStream resolveInput(String systemID) throws KNXMLException
{
try {
try {
final URL loc = new URL(systemID);
return loc.openConnection().getInputStream();
}
catch (final MalformedURLException e) {
return new FileInputStream(systemID);
}
}
catch (final IOException e) {
throw new KNXMLException("error opening " + systemID + ", " + e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.EntityResolver#resolveInput(java.lang.String) |
private String[] readXMLDeclaration(Reader r) throws KNXMLException
{
final StringBuffer buf = new StringBuffer(100);
try {
for (int c = 0; (c = r.read()) != -1 && c != '?';)
buf.append((char) c);
}
catch (final IOException e) {
throw new KNXMLException("reading XML declaration, " + e.getMessage(), buf
.toString(), 0);
}
String s = buf.toString().trim();
String version = null;
String encoding = null;
String standalone = null;
for (int state = 0; state < 3; ++state)
if (state == 0 && s.startsWith("version")) {
version = getAttValue(s = s.substring(7));
s = s.substring(s.indexOf(version) + version.length() + 1).trim();
}
else if (state == 1 && s.startsWith("encoding")) {
encoding = getAttValue(s = s.substring(8));
s = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();
}
else if (state == 1 || state == 2) {
if (s.startsWith("standalone")) {
standalone = getAttValue(s);
if (!standalone.equals("yes") && !standalone.equals("no"))
throw new KNXMLException("invalid standalone pseudo-attribute",
standalone, 0);
break;
}
}
else
throw new KNXMLException("unknown XML declaration pseudo-attribute", s, 0);
return new String[] { version, encoding, standalone };
} | returns array with length 3 and optional entries version, encoding, standalone |
public String getStatusString()
{
switch (status) {
case ErrorCodes.NO_ERROR:
return "the connection was established successfully";
case ErrorCodes.CONNECTION_TYPE:
return "the requested connection type is not supported";
case ErrorCodes.CONNECTION_OPTION:
return "one or more connection options are not supported";
case ErrorCodes.NO_MORE_CONNECTIONS:
return "could not accept new connection (maximum reached)";
case ErrorCodes.TUNNELING_LAYER:
return "the requested tunneling layer is not supported";
default:
return "unknown status";
}
} | Returns a textual representation of the status code.
<p>
@return short description of status as string |
short getStructLength()
{
int len = 2;
if (endpt != null && crd != null)
len += endpt.getStructLength() + crd.getStructLength();
return (short) len;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#getStructLength() |
byte[] toByteArray(ByteArrayOutputStream os)
{
os.write(channelid);
os.write(status);
if (endpt != null && crd != null) {
byte[] buf = endpt.toByteArray();
os.write(buf, 0, buf.length);
buf = crd.toByteArray();
os.write(buf, 0, buf.length);
}
return os.toByteArray();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray
(java.io.ByteArrayOutputStream) |
private Long fetchServiceId(ServiceReference serviceReference) {
return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);
} | Returns the service id with the propertype.
@param serviceReference
@return long value for the service id |
public static DPTXlator createTranslator(int mainNumber, String dptID)
throws KNXException
{
try {
final int main = getMainNumber(mainNumber, dptID);
final MainType type = (MainType) map.get(new Integer(main));
if (type != null)
return type.createTranslator(dptID);
}
catch (final NumberFormatException e) {}
throw new KNXException("main number not found for " + dptID);
} | Creates a DPT translator for the given datapoint type ID.
<p>
The translation behavior of a DPT translator instance is uniquely defined by the
supplied datapoint type ID.
<p>
If the <code>dptID</code> argument is built up the recommended way, that is "<i>main
number</i>.<i>sub number</i>", the <code>mainNumber</code> argument might be
left 0 to use the datapoint type ID only.<br>
Note, that we don't enforce any particular or standardized format on the dptID
structure, so using a different formatted dptID solely without main number argument
results in undefined behavior.
@param mainNumber data type main number, number >= 0; use 0 to infer translator
type from <code>dptID</code> argument only
@param dptID datapoint type ID for selecting a particular kind of value translation
@return the new {@link DPTXlator} object
@throws KNXException on main type not found or creation failed (refer to
{@link MainType#createTranslator(String)}) |
public static DPTXlator createTranslator(DPT dpt) throws KNXException
{
try {
return createTranslator(0, dpt.getID());
}
catch (final KNXException e) {
for (final Iterator i = map.values().iterator(); i.hasNext(); )
try {
return ((MainType) i.next()).createTranslator(dpt);
}
catch (final KNXException ignore) {}
}
throw new KNXException("failed to create translator for DPT " + dpt.getID());
} | Creates a DPT translator for the given datapoint type.
<p>
The translation behavior of a DPT translator instance is uniquely defined by the
supplied datapoint type.
<p>
If translator creation according {@link #createTranslator(int, String)} fails, all
available main types are enumerated to find an appropriate translator.
@param dpt datapoint type selecting a particular kind of value translation
@return the new {@link DPTXlator} object
@throws KNXException if no translator could be found or creation failed |
private static int getMainNumber(int mainNumber, String dptID)
{
return mainNumber != 0 ? mainNumber : Integer.parseInt(dptID.substring(0, dptID
.indexOf('.')));
} | throws NumberFormatException |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle Message Switch Multi Level Request");
logger.debug(String.format("Received Switch Multi Level Request for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SWITCH_MULTILEVEL_SET:
case SWITCH_MULTILEVEL_GET:
case SWITCH_MULTILEVEL_SUPPORTED_GET:
case SWITCH_MULTILEVEL_SUPPORTED_REPORT:
logger.warn(String.format("Command 0x%02X not implemented.", command));
case SWITCH_MULTILEVEL_START_LEVEL_CHANGE:
return;
case SWITCH_MULTILEVEL_STOP_LEVEL_CHANGE:
logger.debug("Process Switch Multi Level Stop Level Change");
// request level after dimming
logger.debug("Requesting level from node {}, endpoint {}", this.getNode().getNodeId(), endpoint);
this.getController().requestValue(this.getNode().getNodeId(), endpoint);
break;
case SWITCH_MULTILEVEL_REPORT:
logger.trace("Process Switch Multi Level Report");
int value = serialMessage.getMessagePayloadByte(offset + 1);
logger.debug(String.format("Switch Multi Level report from nodeId = %d, value = 0x%02X", this.getNode().getNodeId(), value));
Object eventValue;
if (value == 0) {
eventValue = "OFF";
} else if (value < 99) {
eventValue = value;
} else if (value == 99) {
eventValue = "ON";
} else {
// don't send an update event. read back the dimmer value.
this.getController().requestValue(this.getNode().getNodeId(), endpoint);
return;
}
this.level = value;
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEvent.ZWaveEventType.DIMMER_EVENT, this.getNode().getNodeId(), endpoint, eventValue);
this.getController().notifyEventListeners(zEvent);
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
} | {@inheritDoc} |
private static String determineMessage(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
return argumentName != null && !argumentName.isEmpty() ? format(argumentName, expectedType, actualType) : format(expectedType,
actualType);
} | Determines the message to be used, depending on the passed argument name. If if the given argument name is
{@code null} or empty {@code DEFAULT_MESSAGE} will be returned, otherwise a formatted {@code MESSAGE_WITH_NAME}
with the passed name.
@param argumentName
the name of the passed argument
@param expectedType
the expected class of the given argument
@param actualType
the actual class of the given argument
@return {@code MESSAGE_WITH_TYPES} if the given argument name is {@code null} or empty, otherwise a formatted
{@code MESSAGE_WITH_NAME} |
private static String format(@Nullable final Class<?> expectedType, @Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_TYPES, expected, actual);
} | Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_TYPES} with the given types.
@param expectedType
the expected class of the given argument
@param actualType
the actual class of the given argument
@return a formatted string of message with the given argument name |
private static String format(@Nullable final String argumentName, @Nullable final Class<?> expectedType,
@Nullable final Class<?> actualType) {
final String expected = expectedType != null ? expectedType.getName() : NO_TYPE_PLACEHOLDER;
final String actual = actualType != null ? actualType.getName() : NO_TYPE_PLACEHOLDER;
return String.format(MESSAGE_WITH_NAME_AND_TYPES, argumentName, expected, actual);
} | Returns the formatted string {@link IllegalInstanceOfArgumentException#MESSAGE_WITH_NAME_AND_TYPES} with the
given {@code argumentName}.
@param argumentName
the name of the passed argument
@param expectedType
the expected class of the given argument
@param actualType
the actual class of the given argument
@return a formatted string of message with the given argument name |
public void setSpecificDeviceClass(Specific specificDeviceClass) throws IllegalArgumentException {
// The specific Device class does not match the generic device class.
if (specificDeviceClass.genericDeviceClass != Generic.NOT_KNOWN &&
specificDeviceClass.genericDeviceClass != this.genericDeviceClass)
throw new IllegalArgumentException("specificDeviceClass");
this.specificDeviceClass = specificDeviceClass;
} | Set the specific device class of the node.
@param specificDeviceClass the specificDeviceClass to set
@exception IllegalArgumentException thrown when the specific device class does not match
the generic device class. |
private String parseRssFeed(String feed) {
String[] result = feed.split("<br />");
String[] result2 = result[2].split("<BR />");
return result2[0];
} | Parser for actual conditions
@param feed
@return |
private List<String> parseRssFeedForeCast(String feed) {
String[] result = feed.split("<br />");
List<String> returnList = new ArrayList<String>();
String[] result2 = result[2].split("<BR />");
returnList.add(result2[3] + "\n");
returnList.add(result[3] + "\n");
returnList.add(result[4] + "\n");
returnList.add(result[5] + "\n");
returnList.add(result[6] + "\n");
return returnList;
} | Parser for forecast
@param feed
@return |
public XMLReader createXMLReader(String systemID) throws KNXMLException
{
final XMLReader r = (XMLReader) create(DEFAULT_READER);
final EntityResolver res = (EntityResolver) create(DEFAULT_RESOLVER);
final InputStream is = res.resolveInput(systemID);
try {
r.setInput(res.getInputReader(is), true);
}
catch (final KNXMLException e) {
try {
is.close();
}
catch (final IOException ignore) {}
throw e;
}
return r;
} | Creates a {@link XMLReader} to read the XML resource located by the specified
identifier.
<p>
On closing the created XML reader, the {@link Reader} set as input for the XML
reader will get closed as well.
@param systemID location identifier of the XML resource
@return XML reader
@throws KNXMLException if creation of the reader failed or XML resource can't be
resolved |
public XMLWriter createXMLWriter(String systemID) throws KNXMLException
{
final XMLWriter w = (XMLWriter) create(DEFAULT_WRITER);
final EntityResolver res = (EntityResolver) create(DEFAULT_RESOLVER);
final OutputStream os = res.resolveOutput(systemID);
try {
w.setOutput(new OutputStreamWriter(os, "UTF-8"), true);
return w;
}
catch (final UnsupportedEncodingException e) {
try {
os.close();
}
catch (final IOException ignore) {}
throw new KNXMLException("encoding UTF-8 unknown");
}
} | Creates a {@link XMLWriter} to write into the XML resource located by the specified
identifier.
<p>
@param systemID location identifier of the XML resource
@return XML writer
@throws KNXMLException if creation of the writer failed or XML resource can't be
resolved |
public LogService getLogService(String name)
{
synchronized (loggers) {
LogService l = (LogService) loggers.get(name);
if (l == null) {
l = new LogService(name);
loggers.put(name, l);
for (final Iterator i = writers.iterator(); i.hasNext();)
l.addWriter((LogWriter) i.next());
}
return l;
}
} | Queries for a log service with the specified <code>name</code>.
<p>
If the log service with this name already exists in the manager, it will be
returned, otherwise a new log service with this name will be created and added to
the log services listed in the manager.
@param name name of log service, the empty string is not allowed
@return the LogService object |
public boolean addWriter(String logService, LogWriter writer)
{
if (logService != null && logService.length() > 0) {
final LogService l = (LogService) loggers.get(logService);
if (l != null)
l.addWriter(writer);
return l != null;
}
synchronized (loggers) {
writers.add(writer);
for (final Iterator i = loggers.values().iterator(); i.hasNext();)
((LogService) i.next()).addWriter(writer);
return true;
}
} | Adds a log writer, either global or to a particular log service.
<p>
Note that the writer is added to the log service(s) regardless if it was already
added before.<br>
If the writer is added global, it will receive logging information from all log
services that are already registered or will be registered in the future.
@param logService name of a log service; to add the writer global, use an empty
string or <code>null</code>
@param writer log writer to add
@return true if the writer was added successfully,<br>
false a specified log service name was not found
@see LogService#addWriter(LogWriter) |
public void removeWriter(String logService, LogWriter writer)
{
if (logService != null && logService.length() > 0) {
final LogService l = (LogService) loggers.get(logService);
if (l != null)
l.removeWriter(writer);
}
else
synchronized (loggers) {
if (writers.remove(writer))
for (final Iterator i = loggers.values().iterator(); i.hasNext();)
((LogService) i.next()).removeWriter(writer);
}
} | Removes a log writer, either global or from a particular <code>logService</code>.
<p>
Note that for a writer to be removed global, it had to be added global before.
@param logService name of the log service of which the writer will be removed; to
remove the writer global, use an empty string or <code>null</code>
@param writer log writer to remove
@see LogService#removeWriter(LogWriter) |
public static synchronized NetworkBuffer createBuffer(String installationID)
{
if (getBuffer(installationID) != null)
throw new KNXIllegalArgumentException("buffer \"" + installationID
+ "\" already exists");
final NetworkBuffer b = new NetworkBuffer(validateInstID(installationID));
buffers.add(b);
logger.info("created network buffer \"" + installationID + "\"");
return b;
} | Creates a new network buffer for a KNX installation.
<p>
To identify the buffer an unique installation identifier can be given through
<code>installationID</code>.<br>
If <code>null</code> or an empty string is supplied for the installation ID, a
new default ID is generated of the form "Installation [ID]", where [ID] is an
unique incrementing number. Note, the installation ID string is treated case
sensitive.
@param installationID installation identifier for the network buffer, or
<code>null</code>
@return the new network buffer |
public static synchronized void removeBuffer(String installationID)
{
for (final Iterator i = buffers.iterator(); i.hasNext();) {
final NetworkBuffer b = (NetworkBuffer) i.next();
if (b.inst.equals(installationID)) {
i.remove();
while (!b.configs.isEmpty())
b.removeConfiguration((Configuration) b.configs
.get(b.configs.size() - 1));
logger.info("removed network buffer \"" + installationID + "\"");
return;
}
}
} | Removes a network buffer, and all configurations of that buffer.
<p>
For every {@link Configuration} contained in the buffer,
{@link NetworkBuffer#removeConfiguration
(tuwien.auto.calimero.buffer.Configuration)} is called.
@param installationID installation ID of the network buffer to remove |
public static synchronized NetworkBuffer getBuffer(String installationID)
{
for (final Iterator i = buffers.iterator(); i.hasNext();) {
final NetworkBuffer db = (NetworkBuffer) i.next();
if (db.inst.equals(installationID))
return db;
}
return null;
} | Returns the network buffer for the given installation ID.
<p>
@param installationID installation ID for the network buffer
@return the network buffer, or <code>null</code> if no buffer found |
public static Configuration createConfiguration(KNXNetworkLink link,
String installationID)
{
NetworkBuffer b = getBuffer(installationID);
if (b == null)
b = createBuffer(installationID);
return b.createConfiguration(link);
} | Creates a new configuration for the network buffer identified by the installation
ID.
<p>
The configuration is added to the network buffer specified by the installation ID.
If a network buffer with the supplied installation ID does not exist, it will be
created. If <code>null</code> or an empty string is supplied for the installation
ID, a new default ID is generated (see {@link NetworkBuffer#createBuffer(String)}.
<br>
If the supplied <code>link</code> gets closed, the created configuration will get
deactivated (see {@link Configuration#activate(boolean)}), and the buffered link
of the configuration, obtained with {@link Configuration#getBufferedLink()}, will
get closed as well.
@param link KNX network link communicating with the KNX network
@param installationID installation identifier for the network buffer, or
<code>null</code>
@return the new configuration |
public static synchronized void removeConfiguration(Configuration c,
String installationID)
{
for (final Iterator i = buffers.iterator(); i.hasNext();) {
final NetworkBuffer b = (NetworkBuffer) i.next();
if (b.inst.equals(installationID) || installationID == null
&& b.configs.contains(c)) {
b.removeConfiguration(c);
return;
}
}
} | Removes a configuration from the network buffer identified by the installation ID.
<p>
If <code>installationID</code> is <code>null</code>, all network buffers are
searched for the configuration <code>c</code>.<br>
If the network buffer is found containing the specified configuration,
{@link NetworkBuffer#removeConfiguration
(tuwien.auto.calimero.buffer.Configuration)} is called on that buffer.
@param c the configuration to remove
@param installationID installation identifier for the network buffer, or
<code>null</code> |
public Configuration createConfiguration(KNXNetworkLink link)
{
final ConfigImpl c = new ConfigImpl(link);
configs.add(c);
logger.info("created configuration for " + link.getName());
return c;
} | Creates a new configuration for this network buffer.
<p>
If the supplied <code>link</code> gets closed, the created configuration will get
deactivated (see {@link Configuration#activate(boolean)}), and the buffered link
of the configuration, obtained with {@link Configuration#getBufferedLink()}, will
get closed as well.
@param link KNX network link communicating with the KNX network
@return the new configuration |
public void removeConfiguration(Configuration c)
{
if (configs.remove(c)) {
((ConfigImpl) c).unregister();
logger.info("removed configuration of " + c.getBaseLink().getName());
}
} | Removes a configuration from this network buffer.
<p>
The configuration is deactivated and will not receive any further events or
incoming messages from the base network link supplied at creation of that
configuration.
@param c the configuration to remove |
void setCurrentElements(byte[] data)
{
int elems = 0;
for (int i = 0; i < data.length; ++i)
elems = elems << 8 | data[i] & 0xff;
currElems = elems;
}
void setPDT(int type)
{
pdt = (byte) type;
}
} | set 2 or 4 byte data array with element count, big endian |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle Message Sensor Alarm Request");
logger.debug(String.format("Received Sensor Alarm Request for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SENSOR_ALARM_GET:
case SENSOR_ALARM_SUPPORTED_GET:
logger.warn(String.format("Command 0x%02X not implemented.", command));
return;
case SENSOR_ALARM_REPORT:
logger.trace("Process Sensor Alarm Report");
int sourceNode = serialMessage.getMessagePayloadByte(offset + 1);
int alarmTypeCode = serialMessage.getMessagePayloadByte(offset + 2);
int value = serialMessage.getMessagePayloadByte(offset + 3);
logger.debug(String.format("Sensor Alarm report from nodeId = %d", this.getNode().getNodeId()));
logger.debug(String.format("Source node ID = %d", sourceNode));
logger.debug(String.format("Value = 0x%02x", value));
AlarmType alarmType = AlarmType.getAlarmType(alarmTypeCode);
if (alarmType == null) {
logger.error(String.format("Unknown Alarm Type = 0x%02x, ignoring report.", alarmTypeCode));
return;
}
logger.debug(String.format("Alarm Type = %s (0x%02x)", alarmType.getLabel(), alarmTypeCode));
this.alarmValues.put(alarmType, value);
for (Integer alarmValue : this.alarmValues.values()) {
value |= alarmValue;
}
Object eventValue;
if (value == 0) {
eventValue = "CLOSED";
} else {
eventValue = "OPEN";
}
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.SENSOR_EVENT, this.getNode().getNodeId(), endpoint, eventValue);
this.getController().notifyEventListeners(zEvent);
break;
case SENSOR_ALARM_SUPPORTED_REPORT:
logger.debug("Process Sensor Supported Alarm Report");
int numBytes = serialMessage.getMessagePayloadByte(offset + 1);
int manufacturerId = this.getNode().getManufacturer();
int deviceType = this.getNode().getDeviceType();
// Fibaro alarm sensors do not provide a bitmap of alarm types, but list them byte by byte.
if (manufacturerId == 0x010F && deviceType == 0x0700) {
logger.warn("Detected Fibaro FGK - 101 Door / Window sensor, activating workaround for incorrect encoding of supported alarm bitmap.");
for(int i=0; i < numBytes; ++i ) {
int index = serialMessage.getMessagePayloadByte(offset + i + 2);
if(index >= AlarmType.values().length)
continue;
AlarmType alarmTypeToAdd = AlarmType.getAlarmType(index);
this.alarmValues.put(alarmTypeToAdd, 0x00);
logger.debug(String.format("Added alarm type %s (0x%02x)", alarmTypeToAdd.getLabel(), index));
}
} else {
for(int i=0; i < numBytes; ++i ) {
for(int bit = 0; bit < 8; ++bit) {
if( ((serialMessage.getMessagePayloadByte(offset + i +2)) & (1 << bit) ) == 0 )
continue;
int index = (i << 3) + bit;
if(index >= AlarmType.values().length)
continue;
// (n)th bit is set. n is the index for the alarm type enumeration.
AlarmType alarmTypeToAdd = AlarmType.getAlarmType(index);
this.alarmValues.put(alarmTypeToAdd, 0x00);
logger.debug(String.format("Added alarm type %s (0x%02x)", alarmTypeToAdd.getLabel(), index));
}
}
}
this.getNode().advanceNodeStage();
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
} | {@inheritDoc} |
public SerialMessage getMessage(AlarmType alarmType) {
logger.debug("Creating new message for application command SENSOR_ALARM_GET for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_GET,
(byte) alarmType.getKey() };
result.setMessagePayload(newPayload);
return result;
} | Gets a SerialMessage with the SENSOR_ALARM_GET command
@return the serial message |
public SerialMessage getSupportedMessage() {
logger.debug("Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}", this.getNode().getNodeId());
if (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {
logger.warn("Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.");
return null;
}
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
2,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_SUPPORTED_GET };
result.setMessagePayload(newPayload);
return result;
} | Gets a SerialMessage with the SENSOR_ALARM_SUPPORTED_GET command
@return the serial message, or null if the supported command is not supported. |
public Collection<SerialMessage> initialize() {
ArrayList<SerialMessage> result = new ArrayList<SerialMessage>();
if (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {
logger.warn("Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.");
return result;
}
result.add(this.getSupportedMessage());
return result;
} | Initializes the alarm sensor command class. Requests the supported alarm types. |
public static java.util.Date newDateTime() {
return new java.util.Date((System.currentTimeMillis() / SECOND_MILLIS) * SECOND_MILLIS);
} | Create a new DateTime. To the last second. This will not create any
extra-millis-seconds, which may cause bugs when writing to stores such as
databases that round milli-seconds up and down. |
public static java.sql.Date newDate() {
return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS);
} | Create a new Date. To the last day. |
public static java.sql.Time newTime() {
return new java.sql.Time(System.currentTimeMillis() % DAY_MILLIS);
} | Create a new Time, with no date component. |
public static int secondsDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return (int) ((laterDate.getTime() / SECOND_MILLIS) - (earlierDate.getTime() / SECOND_MILLIS));
} | Get the seconds difference |
public static int minutesDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS));
} | Get the minutes difference |
public static int hoursDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS));
} | Get the hours difference |
public static int daysDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));
} | Get the days difference |
public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(startDate);
gc.add(period, amount);
return new java.sql.Time(gc.getTime().getTime());
} | Roll the java.util.Time forward or backward.
@param startDate - The start date
@param period Calendar.YEAR etc
@param amount - Negative to rollbackwards. |
public static java.util.Date rollDateTime(java.util.Date startDate, int period, int amount) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(startDate);
gc.add(period, amount);
return new java.util.Date(gc.getTime().getTime());
} | Roll the java.util.Date forward or backward.
@param startDate - The start date
@param period Calendar.YEAR etc
@param amount - Negative to rollbackwards. |
public static java.sql.Date rollYears(java.util.Date startDate, int years) {
return rollDate(startDate, Calendar.YEAR, years);
} | Roll the years forward or backward.
@param startDate - The start date
@param years - Negative to rollbackwards. |
public static java.sql.Date rollMonths(java.util.Date startDate, int months) {
return rollDate(startDate, Calendar.MONTH, months);
} | Roll the days forward or backward.
@param startDate - The start date
@param months - Negative to rollbackwards. |
public static java.sql.Date rollDays(java.util.Date startDate, int days) {
return rollDate(startDate, Calendar.DATE, days);
} | Roll the days forward or backward.
@param startDate - The start date
@param days - Negative to rollbackwards. |
@SuppressWarnings("deprecation")
public static boolean dateEquals(java.util.Date d1, java.util.Date d2) {
if (d1 == null || d2 == null) {
return false;
}
return d1.getDate() == d2.getDate()
&& d1.getMonth() == d2.getMonth()
&& d1.getYear() == d2.getYear();
} | Checks the day, month and year are equal. |
@SuppressWarnings("deprecation")
public static boolean timeEquals(java.util.Date d1, java.util.Date d2) {
if (d1 == null || d2 == null) {
return false;
}
return d1.getHours() == d2.getHours()
&& d1.getMinutes() == d2.getMinutes()
&& d1.getSeconds() == d2.getSeconds();
} | Checks the hour, minute and second are equal. |
@SuppressWarnings("deprecation")
public static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) {
if (d1 == null || d2 == null) {
return false;
}
return d1.getDate() == d2.getDate()
&& d1.getMonth() == d2.getMonth()
&& d1.getYear() == d2.getYear()
&& d1.getHours() == d2.getHours()
&& d1.getMinutes() == d2.getMinutes()
&& d1.getSeconds() == d2.getSeconds();
} | Checks the second, hour, month, day, month and year are equal. |
public static Object toObject(Class<?> clazz, Object value) throws ParseException {
if (value == null) {
return null;
}
if (clazz == null) {
return value;
}
if (java.sql.Date.class.isAssignableFrom(clazz)) {
return toDate(value);
}
if (java.sql.Time.class.isAssignableFrom(clazz)) {
return toTime(value);
}
if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {
return toTimestamp(value);
}
if (java.util.Date.class.isAssignableFrom(clazz)) {
return toDateTime(value);
}
return value;
} | Convert an Object of type Class to an Object. |
public static java.util.Date getDateTime(Object value) {
try {
return toDateTime(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | Convert an Object to a DateTime, without an Exception |
public static java.util.Date toDateTime(Object value) throws ParseException {
if (value == null) {
return null;
}
if (value instanceof java.util.Date) {
return (java.util.Date) value;
}
if (value instanceof String) {
if ("".equals((String) value)) {
return null;
}
return IN_DATETIME_FORMAT.parse((String) value);
}
return IN_DATETIME_FORMAT.parse(value.toString());
} | Convert an Object to a DateTime. |
public static java.sql.Date getDate(Object value) {
try {
return toDate(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | Convert an Object to a Date, without an Exception |
public static java.sql.Date toDate(Object value) throws ParseException {
if (value == null) {
return null;
}
if (value instanceof java.sql.Date) {
return (java.sql.Date) value;
}
if (value instanceof String) {
if ("".equals((String) value)) {
return null;
}
return new java.sql.Date(IN_DATE_FORMAT.parse((String) value).getTime());
}
return new java.sql.Date(IN_DATE_FORMAT.parse(value.toString()).getTime());
} | Convert an Object to a Date. |
public static java.sql.Time getTime(Object value) {
try {
return toTime(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | Convert an Object to a Time, without an Exception |
public static java.sql.Time toTime(Object value) throws ParseException {
if (value == null) {
return null;
}
if (value instanceof java.sql.Time) {
return (java.sql.Time) value;
}
if (value instanceof String) {
if ("".equals((String) value)) {
return null;
}
return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());
}
return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());
} | Convert an Object to a Time. |
public static java.sql.Timestamp getTimestamp(Object value) {
try {
return toTimestamp(value);
} catch (ParseException pe) {
pe.printStackTrace();
return null;
}
} | Convert an Object to a Timestamp, without an Exception |
public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {
if (value == null) {
return null;
}
if (value instanceof java.sql.Timestamp) {
return (java.sql.Timestamp) value;
}
if (value instanceof String) {
if ("".equals((String) value)) {
return null;
}
return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());
}
return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());
} | Convert an Object to a Timestamp. |
@SuppressWarnings("deprecation")
public static boolean isTimeInRange(java.sql.Time start, java.sql.Time end, java.util.Date d) {
d = new java.sql.Time(d.getHours(), d.getMinutes(), d.getSeconds());
if (start == null || end == null) {
return false;
}
if (start.before(end) && (!(d.after(start) && d.before(end)))) {
return false;
}
if (end.before(start) && (!(d.after(end) || d.before(start)))) {
return false;
}
return true;
} | Tells you if the date part of a datetime is in a certain time range. |
public static Trajectory combineTrajectory(Trajectory a, Trajectory b){
if(a.getDimension()!=b.getDimension()){
throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension");
}
if(a.size()!=b.size()){
throw new IllegalArgumentException("Combination not possible: The trajectorys does not "
+ "have the same number of steps a="+a.size() + " b="+b.size());
}
Trajectory c = new Trajectory(a.getDimension());
for(int i = 0 ; i < a.size(); i++){
Point3d pos = new Point3d(a.get(i).x+b.get(i).x,
a.get(i).y+b.get(i).y,
a.get(i).z+b.get(i).z);
c.add(pos);
}
return c;
} | Combines two trajectories by adding the corresponding positions. The trajectories have to have the same length.
@param a The first trajectory
@param b The second trajectory
@return The combined trajectory |
public static Trajectory concactTrajectorie(Trajectory a, Trajectory b){
if(a.getDimension()!=b.getDimension()){
throw new IllegalArgumentException("Combination not possible: The trajectorys does not have the same dimension");
}
Trajectory c = new Trajectory(a.getDimension());
for(int i = 0 ; i < a.size(); i++){
Point3d pos = new Point3d(a.get(i).x,
a.get(i).y,
a.get(i).z);
c.add(pos);
}
double dx = a.get(a.size()-1).x - b.get(0).x;
double dy = a.get(a.size()-1).y - b.get(0).y;
double dz = a.get(a.size()-1).z - b.get(0).z;
for(int i = 1 ; i < b.size(); i++){
Point3d pos = new Point3d(b.get(i).x+dx,
b.get(i).y+dy,
b.get(i).z+dz);
c.add(pos);
}
return c;
} | Concatenates the trajectory a and b
@param a The end of this trajectory will be connected to the start of trajectory b
@param b The start of this trajectory will be connected to the end of trajectory a
@return Concatenated trajectory |
public static Trajectory resample(Trajectory t, int n){
Trajectory t1 = new Trajectory(2);
for(int i = 0; i < t.size(); i=i+n){
t1.add(t.get(i));
}
return t1;
} | Resamples a trajectory
@param t Trajectory to resample
@param n Resample rate
@return Returns a resampled trajectory which contains every n'th position of t |
public static ArrayList<Trajectory> splitTrackInSubTracks(Trajectory t, int windowWidth, boolean overlapping){
int increment = 1;
if(overlapping==false){
increment=windowWidth;
}
ArrayList<Trajectory> subTrajectories = new ArrayList<Trajectory>();
boolean trackEndReached = false;
for(int i = 0; i < t.size(); i=i+increment)
{
int upperBound = i+(windowWidth);
if(upperBound>t.size()){
upperBound=t.size();
trackEndReached=true;
}
Trajectory help = new Trajectory(2, i);
for(int j = i; j < upperBound; j++){
help.add(t.get(j));
}
subTrajectories.add(help);
if(trackEndReached){
i=t.size();
}
}
return subTrajectories;
} | Splits a trajectory in overlapping / non-overlapping sub-trajectories.
@param t
@param windowWidth Window width. Each sub-trajectory will have this length
@param overlapping Allows the window to overlap
@return ArrayList with sub-trajectories |
public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){
Trajectory track = null;
for(int i = 0; i < t.size() ; i++){
if(t.get(i).getID()==id){
track = t.get(i);
break;
}
}
return track;
} | Finds trajectory by ID
@param t List of Trajectories
@param id ID of the trajectorie
@return Trajectory with ID=id |
public QueueItem getNextIndication()
{
synchronized (indicationKeys) {
if (indicationKeys.isEmpty())
throw new KNXIllegalStateException("no indications");
return ((LDataObjectQueue) indicationKeys.remove(0)).getItem();
}
} | Returns the next available indication.
<p>
The items with the cEMI frame indications are returned in FIFO order according the
time they were supplied to the filter and buffered in the first place, i.e. an
earlier accepted frame is returned before an frame accepted at some later time.<br>
Every item is only returned once by this method, after that it is no longer marked
as new and will not cause {@link #hasNewIndication()} to return <code>true</code>
for it.<br>
If no indication is available, throws {@link KNXIllegalStateException}.
<p>
Nevertheless, the queued item might be retrieved directly through the used cache
(which is obtained by {@link Configuration#getCache()}). Whether or not an
returned item is completely consumed from the queue in the cache, i.e. removed from
the cache object in the cache, is specified in the {@link LDataObjectQueue}
containing the item at creation time (which is a task of the network filter).
<p>
Note, if the accessed queue in the cache was modified between the time the
indication was added and this method call in such a way, that the original
indication is not available anymore (for example by removal or emptied queue), that
indication might be skipped or an empty QueueItem is returned.
@return queue item containing cEMI frame indication |
public static KNXAddress create(XMLReader r) throws KNXMLException
{
if (r.getPosition() != XMLReader.START_TAG)
r.read();
if (r.getPosition() == XMLReader.START_TAG) {
final String type = r.getCurrent().getAttribute(ATTR_TYPE);
if (GroupAddress.ATTR_GROUP.equals(type))
return new GroupAddress(r);
else if (IndividualAddress.ATTR_IND.equals(type))
return new IndividualAddress(r);
}
throw new KNXMLException("not a KNX address", null, r.getLineNumber());
} | Creates a KNX address from xml input.
<p>
The KNX address element is expected to be the current or next element from the
parser.
@param r a XML reader
@return the created KNXAddress, either of subtype {@link GroupAddress} or
{@link IndividualAddress}
@throws KNXMLException if the XML element is no KNX address, on unknown address
type or wrong address syntax |
public static KNXAddress create(String address) throws KNXFormatException
{
if (address.indexOf('.') != -1)
return new IndividualAddress(address);
return new GroupAddress(address);
} | Creates a KNX address from a string <code>address</code> representation.
<p>
An address level separator of type '.' found in <code>address</code> indicates an
individual address, i.e. an {@link IndividualAddress} is created, otherwise a
{@link GroupAddress} is created.<br>
Allowed separators are '.' or '/', mutually exclusive.
@param address string containing the KNX address
@return the created KNX address, either of subtype {@link GroupAddress} or
{@link IndividualAddress}
@throws KNXFormatException thrown on unknown address type, wrong address syntax or
wrong separator used |
public void save(XMLWriter w) throws KNXMLException
{
final List att = new ArrayList();
att.add(new Attribute(ATTR_TYPE, getType()));
w.writeElement(TAG_ADDRESS, att, Integer.toString(address));
w.endElement();
} | Writes the KNX address in XML format to the supplied writer.
<p>
@param w a XML writer
@throws KNXMLException on output error |
public Dictionary invoke(Dictionary args) throws Exception {
String value = time.getCurrentTime();
Hashtable result = new Hashtable();
result.put(RESULT_STATUS,value);
return result;
} | /* (non-Javadoc)
@see org.osgi.service.upnp.UPnPAction#invoke(java.util.Dictionary) |
public void setPropertyDestinationType(Class<?> clazz, String propertyName,
TypeReference<?> destinationType) {
propertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType);
} | set the property destination type for given property
@param propertyName
@param destinationType |
public boolean matches(final HTTPRequest request) {
if (varyHeaders.containsKey("ALL")) return false;
Headers headers = request.getAllHeaders();
for (Map.Entry<String, String> varyEntry : varyHeaders.entrySet()) {
if (request.getChallenge().isPresent() && varyEntry.getKey().equals(HeaderConstants.AUTHORIZATION)) {
if (!request.getChallenge().get().getIdentifier().equals(varyEntry.getValue())) {
return false;
}
}
else {
List<Header> requestHeaderValue = headers.getHeaders(varyEntry.getKey());
boolean valid = requestHeaderValue.isEmpty() ? varyEntry.getValue() == null : headers.getFirstHeader(varyEntry.getKey()).get().getValue().equals(varyEntry.getValue());
if (!valid) {
return false;
}
}
}
List<Preference> preferences = new ArrayList<>();
preferences.addAll(headers.getAccept());
preferences.addAll(headers.getAcceptCharset());
preferences.addAll(headers.getAcceptLanguage());
return !(varyHeaders.isEmpty() && !preferences.isEmpty());
} | todo: cleanup this |
public void addConverter(int index, IConverter converter) {
converterList.add(index, converter);
if (converter instanceof IContainerConverter) {
IContainerConverter containerConverter = (IContainerConverter) converter;
if (containerConverter.getElementConverter() == null) {
containerConverter.setElementConverter(elementConverter);
}
}
} | add converter at given index. The index can be changed during conversion
if canReorder is true
@param index
@param converter |
public static SPIProviderResolver getInstance(ClassLoader cl)
{
SPIProviderResolver resolver = (SPIProviderResolver)ServiceLoader.loadService(SPIProviderResolver.class.getName(), DEFAULT_SPI_PROVIDER_RESOLVER, cl);
return resolver;
} | Get the SPIProviderResolver instance using the provided classloader for lookup
@param cl classloader to use for lookup
@return instance of this class |
private Directive createDirective(
final String name,
final String value,
final List<Parameter> params) {
if (isQuoted(value)) {
return new QuotedDirective(name, value, params);
}
if (HeaderConstants.LINK_HEADER.equals(name)) {
return new LinkDirective(value, params);
}
return new Directive(name, value, params);
} | Creates a header element.
Called from {@link #parseDirective}.
@return a header element representing the argument |
static Parameter createParameter(final String name, final String value) {
if (value != null && isQuoted(value)) {
return new QuotedParameter(name, value);
}
return new Parameter(name, value);
} | Creates a Parameter
@param name the name
@param value the value, or <code>null</code>
@return a name-value pair representing the arguments |
public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) {
String value = null;
Annotation annotation = classType.getAnnotation(annotationType);
if (annotation != null) {
try {
value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);
} catch (Exception ex) {}
}
return value;
} | Get the value of a Annotation in a class declaration.
@param classType
@param annotationType
@param attributeName
@return the value of the annotation as String or null if something goes wrong |
private Long string2long(String text, DateTimeFormat fmt) {
// null or "" returns null
if (text == null) return null;
text = text.trim();
if (text.length() == 0) return null;
Date date = fmt.parse(text);
return date != null ? UTCDateBox.date2utc(date) : null;
} | Parses the supplied text and converts it to a Long
corresponding to that midnight in UTC on the specified date.
@return null if it fails to parsing using the specified
DateTimeFormat |
private String long2string(Long value, DateTimeFormat fmt) {
// for html5 inputs, use "" for no value
if (value == null) return "";
Date date = UTCDateBox.utc2date(value);
return date != null ? fmt.format(date) : null;
} | Formats the supplied value using the specified DateTimeFormat.
@return "" if the value is null |
@Override
protected void init(DifferentiableBatchFunction function, IntDoubleVector point) {
super.init(function, point);
this.accumLr = new DoubleArrayList();
this.iterOfLastStep = new int[function.getNumDimensions()];
Arrays.fill(iterOfLastStep, -1);
} | Initializes all the parameters for optimization. |
@Override
protected void init(DifferentiableBatchFunction function, IntDoubleVector point) {
super.init(function, point);
this.iterOfLastStep = new int[function.getNumDimensions()];
Arrays.fill(iterOfLastStep, -1);
this.gradSumSquares = new double[function.getNumDimensions()];
Arrays.fill(gradSumSquares, prm.initialSumSquares);
} | Initializes all the parameters for optimization. |
private double getLearningRate(int i) {
if (gradSumSquares[i] < 0) {
throw new RuntimeException("Gradient sum of squares entry is < 0: " + gradSumSquares[i]);
}
double learningRate = prm.eta / (prm.constantAddend + Math.sqrt(gradSumSquares[i]));
assert !Double.isNaN(learningRate);
if (learningRate == Double.POSITIVE_INFINITY) {
if (gradSumSquares[i] != 0.0) {
log.warn("Gradient was non-zero but learningRate hit positive infinity: " + gradSumSquares[i]);
}
// Just return zero. The gradient is probably 0.0.
return 0.0;
}
return learningRate;
} | Gets the learning rate for the current iteration.
@param i The index of the current model parameter. |
public static RgbaColor from(String color) {
if (color.startsWith("#")) {
return fromHex(color);
}
else if (color.startsWith("rgba")) {
return fromRgba(color);
}
else if (color.startsWith("rgb")) {
return fromRgb(color);
}
else if (color.startsWith("hsla")) {
return fromHsla(color);
}
else if (color.startsWith("hsl")) {
return fromHsl(color);
}
else {
return getDefaultColor();
}
} | Parses an RgbaColor from a hexadecimal, rgb, rgba, hsl, or hsla
value.
@return returns the parsed color |
public static RgbaColor fromHex(String hex) {
if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();
// #rgb
if (hex.length() == 4) {
return new RgbaColor(parseHex(hex, 1, 2),
parseHex(hex, 2, 3),
parseHex(hex, 3, 4));
}
// #rrggbb
else if (hex.length() == 7) {
return new RgbaColor(parseHex(hex, 1, 3),
parseHex(hex, 3, 5),
parseHex(hex, 5, 7));
}
else {
return getDefaultColor();
}
} | Parses an RgbaColor from a hexadecimal value.
@return returns the parsed color |
public static RgbaColor fromRgb(String rgb) {
if (rgb.length() == 0) return getDefaultColor();
String[] parts = getRgbParts(rgb).split(",");
if (parts.length == 3) {
return new RgbaColor(parseInt(parts[0]),
parseInt(parts[1]),
parseInt(parts[2]));
}
else {
return getDefaultColor();
}
} | Parses an RgbaColor from an rgb value.
@return the parsed color |
public static RgbaColor fromRgba(String rgba) {
if (rgba.length() == 0) return getDefaultColor();
String[] parts = getRgbaParts(rgba).split(",");
if (parts.length == 4) {
return new RgbaColor(parseInt(parts[0]),
parseInt(parts[1]),
parseInt(parts[2]),
parseFloat(parts[3]));
}
else {
return getDefaultColor();
}
} | Parses an RgbaColor from an rgba value.
@return the parsed color |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.