Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (c) OSGi Alliance (2004, 2012). All Rights Reserved.
   
    * 
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  package org.osgi.service.dmt;
  
  import java.util.Arrays;
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Map;
An immutable data structure representing the contents of a leaf or interior node. This structure represents only the value and the format property of the node, all other properties (like MIME type) can be set and read using the DmtSession interface.

Different constructors are available to create nodes with different formats. Nodes of null format can be created using the static NULL_VALUE constant instance of this class.

FORMAT_RAW_BINARY and FORMAT_RAW_STRING enable the support of future data formats. When using these formats, the actual format name is specified as a String. The application is responsible for the proper encoding of the data according to the specified format.

Version:
$Id: 6f90093efc936187d6e78d3dc02cd8c7e816f45a $
Immutable:
  
  public final class DmtData {

The node holds an OMA DM int value.
  
  	public static final int		FORMAT_INTEGER		= 0x0001;

The node holds an OMA DM float value.
  
  	public static final int		FORMAT_FLOAT		= 0x0002;

The node holds an OMA DM chr value.
  
  	public static final int		FORMAT_STRING		= 0x0004;

The node holds an OMA DM bool value.
  
  	public static final int		FORMAT_BOOLEAN		= 0x0008;

The node holds an OMA DM date value.
  
  	public static final int		FORMAT_DATE			= 0x0010;

The node holds an OMA DM time value.
  
  	public static final int		FORMAT_TIME			= 0x0020;

The node holds an OMA DM bin value. The value of the node corresponds to the Java byte[] type.
  
  	public static final int		FORMAT_BINARY		= 0x0040;

The node holds an OMA DM b64 value. Like FORMAT_BINARY, this format is also represented by the Java byte[] type, the difference is only in the corresponding OMA DM format. This format does not affect the internal storage format of the data as byte[]. It is intended as a hint for the external representation of this data. Protocol Adapters can use this hint for their further processing.
  
  	public static final int		FORMAT_BASE64		= 0x0080;

The node holds an OMA DM xml value.
  
  	public static final int		FORMAT_XML			= 0x0100;

The node holds an OMA DM null value. This corresponds to the Java null type.
 
 	public static final int		FORMAT_NULL			= 0x0200;

Format specifier of an internal node. An interior node can hold a Java object as value (see DmtData(java.lang.Object) and getNode()). This value can be used by Java programs that know a specific URI understands the associated Java type. This type is further used as a return value of the MetaNode.getFormat() method for interior nodes.
 
 	public static final int		FORMAT_NODE			= 0x0400;

The node holds raw protocol data encoded as String. The getFormatName() method can be used to get the actual format name.
 
 	public static final int		FORMAT_RAW_STRING	= 0x0800;

The node holds raw protocol data encoded in binary format. The getFormatName() method can be used to get the actual format name.
 
 	public static final int		FORMAT_RAW_BINARY	= 0x1000;

The node holds a long value. The getFormatName() method can be used to get the actual format name.

Since:
2.0
 
 	public static final int		FORMAT_LONG			= 0x2000;

The node holds a Date object. If the getTime() equals zero then the date time is not known. If the getTime() is negative it must be interpreted as a relative number of milliseconds.

Since:
2.0
 
 	public static final int		FORMAT_DATE_TIME	= 0x4000;
 
 	// FORMAT_NAMES must be initialized before any constructor is called.
 	private static final Map	FORMAT_NAMESnew HashMap();
 	static {
 		.put(new Integer(), "boolean");
 		.put(new Integer(), "integer");
 	}

Constant instance representing a leaf node of null format.
 
 	public static final DmtData	NULL_VALUEnew DmtData();

Constant instance representing a boolean true value.

Since:
2.0
 
 	public static final DmtData	TRUE_VALUEnew DmtData(true);

Constant instance representing a boolean false value.

Since:
2.0
 
 	public static final DmtData	FALSE_VALUEnew DmtData(false);
 
 	private final int			format;
 	private final Object		value;
 
 	/*
 	 * For format names, can be overridden by raw formats
 	 */
 	private String				formatName;

Create a DmtData instance of null format. This constructor is private and used only to create the public NULL_VALUE constant.
 
 	private DmtData() {
 		this(nullnull);
 	}

Create a DmtData instance of chr format with the given string value. The null string argument is valid.

Parameters:
string the string value to set
 
 	public DmtData(String string) {
 		this(stringnull);
 	}

Create a DmtData instance of dateTime format with the given Date value. The given Date value must be a non-null Date object.

Parameters:
date the Date object to set
 
 	public DmtData(Date date) {
 		if (date == null)
 			throw new NullPointerException("The date argument is null.");
 		this. = date;
 	}

Create a DmtData instance of node format with the given object value. The value represents complex data associated with an interior node.

Certain interior nodes can support access to their subtrees through such complex values, making it simpler to retrieve or update all leaf nodes in a subtree.

The given value must be a non-null immutable object.

Parameters:
complex the complex data object to set
 
 	public DmtData(Object complex) {
 		if (complex == null)
 			throw new NullPointerException("Complex data argument is null.");
 		 = complex;
 	}

Create a DmtData instance of the specified format and set its value based on the given string. Only the following string-based formats can be created using this constructor:
  • FORMAT_STRING - value can be any string
  • FORMAT_XML - value must contain an XML fragment (the validity is not checked by this constructor)
  • FORMAT_DATE - value must be parsable to an ISO 8601 calendar date in complete representation, basic format (pattern CCYYMMDD)
  • FORMAT_TIME - value must be parsable to an ISO 8601 time of day in either local time, complete representation, basic format (pattern hhmmss) or Coordinated Universal Time, basic format (pattern hhmmssZ)
* The null string argument is only valid if the format is string or XML.

Parameters:
value the string, XML, date, or time value to set
format the format of the DmtData instance to be created, must be one of the formats specified above
Throws:
java.lang.IllegalArgumentException if format is not one of the allowed formats, or value is not a valid string for the given format
java.lang.NullPointerException if a string, XML, date, or time is constructed and value is null
 
 	public DmtData(String valueint format) {
 		this(valueformatnull);
 		if ( format ==  || format ==  || format== || format==)
 			    return;
 
 		throw new IllegalArgumentException("Wrong format for DmtData(String,int), format must be one of FORMAT_STRING, FORMAT_XML, FORMAT_DATE, or FORMAT_TIME");
 	}

Create a DmtData instance of int format and set its value.

Parameters:
integer the integer value to set
 
 	public DmtData(int integer) {
 		this(new Integer(integer), null);
 	}

Create a DmtData instance of float format and set its value.

Parameters:
flt the float value to set
 
 	public DmtData(float flt) {
 		this(new Float(flt), null);
 	}

Create a DmtData instance of long format and set its value.

Parameters:
lng the long value to set
Since:
2.0
 
 	public DmtData(long lng) {
 		this(new Long(lng), null);
 	}

Create a DmtData instance of bool format and set its value.

Parameters:
bool the boolean value to set
 
 	public DmtData(boolean bool) {
 		this(Boolean.valueOf(bool), null);
 	}

Create a DmtData instance of bin format and set its value.

Parameters:
bytes the byte array to set, must not be null
Throws:
java.lang.NullPointerException if bytes is null
 
 	public DmtData(byte[] bytes) {
 		this(bytesnull);
 	}

Create a DmtData instance of bin or b64 format and set its value. The chosen format is specified by the base64 parameter.

Parameters:
bytes the byte array to set, must not be null
base64 if true, the new instance will have b64 format, if false, it will have bin format
Throws:
java.lang.NullPointerException if bytes is null
 
 	public DmtData(byte[] bytesboolean base64) {
 		this(bytesbase64 ?  : null);
 	}

Create a DmtData instance of the specified format and set its value based on the given byte[]. Only the following byte[] based formats can be created using this constructor:

Parameters:
bytes the byte array to set, must not be null
format the format of the DmtData instance to be created, must be one of the formats specified above
Throws:
java.lang.IllegalArgumentException if format is not one of the allowed formats
java.lang.NullPointerException if bytes is null
 
 	public DmtData(byte[] bytesint format) {
 		this(bytesformatnull);
 		if (format ==  || format == )
 			return;
 				"Invalid format for DmtDate(byte[],format), only FORMAT_BINARY and FORMAT_BASE64 are allowed");
 	}

Create a DmtData instance in FORMAT_RAW_STRING format. The data is provided encoded as a String. The actual data format is specified in formatName. The encoding used in data must conform to this format.

Parameters:
formatName the name of the format, must not be null
data the data encoded according to the specified format, must not be null
Throws:
java.lang.NullPointerException if formatName or data is null
 
 	public DmtData(String formatNameString data) {
 		this(data.toString(), formatName.toString());
 	}
 
 	/*
 	 * Constructor used by all others.
 	 * 
 	 * @param value The value
 	 * 
 	 * @param format The format
 	 * 
 	 * @param formatName The name of the format, can be null will then be set to
 	 * the format name
 	 */
 
 	private DmtData(Object valueint formatString formatName) {
 		this. = value;
 		this. = format;
 		this. = formatName;
 	}

Create a DmtData instance in FORMAT_RAW_BINARY format. The data is provided encoded as binary. The actual data format is specified in formatName. The encoding used in data must conform to this format.

Parameters:
formatName the name of the format, must not be null
data the data encoded according to the specified format, must not be null
Throws:
java.lang.NullPointerException if formatName or data is null
 
 	public DmtData(String formatNamebyte[] data) {
 		this(dataformatName);
 		if (formatName == null)
 			throw new NullPointerException("Format name argument is null.");
 	}
 
 	/*
 	 * Validate the setup
 	 */
 	private void validate() {
 		Class c;
 		switch () {
 			case  :
 				c = Integer.class;
 				break;
 
 			case  :
 				c = Float.class;
 				break;
 
 			case  :
 				c = String.class;
 				break;
 
 			case  :
 				c = String.class;
 				break;
 
 			case  :
 			case  :
 				c = String.class;
 				if ( != null) {
 				    break;
 				} else {
 					return;
 				}
 
 				c = String.class;
 				break;
 
 			case  :
 				c = Boolean.class;
 				break;
 
 			case  :
 			case  :
 				if ( != null) {
 				    c = byte[].class;
 				    break;
 				}
 				throw new NullPointerException("The bytes argument is null.");
 
 			case  :
 				if ( != null)
 							"Format is null but value is not ");
 				else
 					return;
 
 			case  :
 				c = Object.class;
 				break;
 
 			case  :
 				c = Long.class;
 				break;
 
 			default :
 						"Invalid format number for DmtData " + );
 
 		}
 		if (!c.isInstance())
 					"Invalid type type for DmtData, expected " + c.getClass()
 							+ " but have " + .getClass());
 
 	}

Gets the value of a node with string (chr) format.

Returns:
the string value
Throws:
DmtIllegalStateException if the format of the node is not string
 
 	public String getString() {
 		if ( == )
 			return (String;
 
 		throw new DmtIllegalStateException("DmtData value is not string.");
 	}

Gets the value of a node with date format. The returned date string is formatted according to the ISO 8601 definition of a calendar date in complete representation, basic format (pattern CCYYMMDD).

Returns:
the date value
Throws:
DmtIllegalStateException if the format of the node is not date
 
 	public String getDate() {
 		if ( == )
 			return (String;
 
 		throw new DmtIllegalStateException("DmtData value is not date.");
 	}

Gets the value of a node with time format. The returned time string is formatted according to the ISO 8601 definition of the time of day. The exact format depends on the value the object was initialized with: either local time, complete representation, basic format (pattern hhmmss ) or Coordinated Universal Time, basic format (pattern hhmmssZ).

Returns:
the time value
Throws:
DmtIllegalStateException if the format of the node is not time
 
 	public String getTime() {
 		if ( == )
 			return (String;
 
 		throw new DmtIllegalStateException("DmtData value is not time.");
 	}

Gets the value of a node with dateTime format.

Returns:
the Date value
Throws:
DmtIllegalStateException if the format of the node is not time
Since:
2.0
 
 	public Date getDateTime() {
 			return (Date;
 
 		throw new DmtIllegalStateException("DmtData value is not dateTime.");
 	}

Gets the value of a node with xml format.

Returns:
the XML value
Throws:
DmtIllegalStateException if the format of the node is not xml
 
 	public String getXml() {
 		if ( == )
 			return (String;
 
 		throw new DmtIllegalStateException("DmtData value is not XML.");
 	}

Gets the value of a node with integer (int) format.

Returns:
the integer value
Throws:
DmtIllegalStateException if the format of the node is not integer
 
 	public int getInt() {
 			return ((Integer).intValue();
 
 		throw new DmtIllegalStateException("DmtData value is not integer.");
 	}

Gets the value of a node with long format.

Returns:
the long value
Throws:
DmtIllegalStateException if the format of the node is not long
Since:
2.0
 
 	public long getLong() {
 		if ( == )
 			return ((Long).longValue();
 
 		throw new DmtIllegalStateException("DmtData value is not long.");
 	}

Gets the value of a node with float format.

Returns:
the float value
Throws:
DmtIllegalStateException if the format of the node is not float
 
 	public float getFloat() {
 		if ( == )
 			return ((Float).floatValue();
 
 		throw new DmtIllegalStateException("DmtData value is not float.");
 	}

Gets the value of a node with boolean (bool) format.

Returns:
the boolean value
Throws:
DmtIllegalStateException if the format of the node is not boolean
 
 	public boolean getBoolean() {
 			return ((Boolean).booleanValue();
 
 		throw new DmtIllegalStateException("DmtData value is not boolean.");
 	}

Gets the value of a node with binary (bin) format.

Returns:
the binary value
Throws:
DmtIllegalStateException if the format of the node is not binary
 
 	public byte[] getBinary() {
 		if ( == ) {
 			return copyBytes();
 		}
 
 		throw new DmtIllegalStateException("DmtData value is not a byte array.");
 	}
 
 	/*
 	 * Copy bytes to a new buffer
 	 * 
 	 * @return the copied bytes
 	 */
 	private byte[] copyBytes() {
 		byte[] bytes = (byte[]) ;
 		byte[] bytesCopy = new byte[bytes.length];
 		System.arraycopy(bytes, 0, bytesCopy, 0, bytes.length);
 		return bytesCopy;
 	}

Gets the value of a node in raw binary (FORMAT_RAW_BINARY) format.

Returns:
the data value in raw binary format
Throws:
DmtIllegalStateException if the format of the node is not raw binary
 
 	public byte[] getRawBinary() {
 			return copyBytes();
 
 				"DmtData value is not in raw binary format.");
 	}

Gets the value of a node in raw String ( FORMAT_RAW_STRING) format.

Returns:
the data value in raw String format
Throws:
DmtIllegalStateException if the format of the node is not raw String
 
 	public String getRawString() {
 			return (String;
 
 				"DmtData value is not in raw string format.");
 	}

Gets the value of a node with base 64 (b64) format.

Returns:
the binary value
Throws:
DmtIllegalStateException if the format of the node is not base 64.
 
 	public byte[] getBase64() {
 		if ( == ) {
 			return copyBytes();
 		}
 
 				"DmtData value is not in base 64 format.");
 	}

Gets the complex data associated with an interior node (node format).

Certain interior nodes can support access to their subtrees through complex values, making it simpler to retrieve or update all leaf nodes in the subtree.

Returns:
the data object associated with an interior node
Throws:
DmtIllegalStateException if the format of the data is not node
 
 	public Object getNode() {
 		if ( == )
 			return ;
 
 				"DmtData does not contain interior node data.");
 	}

Get the node's format, expressed in terms of type constants defined in this class. Note that the 'format' term is a legacy from OMA DM, it is more customary to think of this as 'type'.

Returns:
the format of the node
 
 	public int getFormat() {
 		return ;
 	}

Returns the format of this DmtData as String. For the predefined data formats this is the OMA DM defined name of the format. For FORMAT_RAW_STRING and FORMAT_RAW_BINARY this is the format specified when the object was created.

Returns:
the format name as String
 
 	public String getFormatName() {
 		if ( == null)
 		return ;
 	}

Get the size of the data. The returned value depends on the format of data in the node:

Returns:
the size of the data stored by this object
 
 	public int getSize() {
 		switch () {
 			case  :
 			case  :
 			case  :
 			case  :
 				if ( != null) {
 				    return ((String).length();
 				} else {
 					return 0;
 				}
 			case  :
 			case  :
 				return ((byte[]) ).length;
 			case  :
 			case  :
 				return 4;
 			case  :
 				return 1;
 			case  :
 				return -1;
 			case  :
 				return 8;
 			case  :
 				return 0;
 		}
 
 		return 0; // never reached
 	}

Gets the string representation of the DmtData. This method works for all formats.

For string format data - including FORMAT_RAW_STRING - the string value itself is returned, while for XML, date, time, integer, float, boolean, long and node formats the string form of the value is returned. Binary - including FORMAT_RAW_BINARY - base64 data is represented by two-digit hexadecimal numbers for each byte separated by spaces. The NULL_VALUE data has the string form of " null". Data of string or XML format containing the Java null value is represented by an empty string. DateTime data is formatted as yyyy-MM-dd'T'HH:mm:SS'Z').

Returns:
the string representation of this DmtData instance
 
 	public String toString() {
 		switch () {
 			case  :
 			case  :
 			case  :
 			case  :
 				if ( != null) {
 				    return (String;
 				} else {
 					return "";
 				}
 
 			case  :
 			case  :
 			case  :
 			case  :
 			case  :
 				return .toString();
 
 			case  :
 			case  :
 				return getHexDump((byte[]) );
 
 			case  :
 				return "null";
 
 				// unfortunately SimpleDateFormat is not thread safe :-(
 						"yyyy-MM-dd'T'HH:mm:SS'Z'");
 				sf.setTimeZone(TimeZone.getTimeZone("UTC"));
 				return sf.format();
 
 			default :
 				throw new IllegalStateException("Invalid format " + );
 		}
 	}

Compares the specified object with this DmtData instance. Two DmtData objects are considered equal if their format is the same, and their data (selected by the format) is equal.

In case of FORMAT_RAW_BINARY and FORMAT_RAW_STRING the textual name of the data format - as returned by getFormatName() - must be equal as well.

Parameters:
obj the object to compare with this DmtData
Returns:
true if the argument represents the same DmtData as this object
 
 	public boolean equals(Object obj) {
 		if (!(obj instanceof DmtData))
 			return false;
 
 		DmtData other = (DmtDataobj;
 
 		if ( != other.format)
 			return false;
 
 		if ( != null) {
             if (!.equals(other.formatName)) {
             	return false;
             }
 		}
 
 		if ( == null)
 			if (other.value == null)
 				return true;
 			else
 				return false;
 
 		if (.equals(other.value)) {
 			return true;
 		}
 
         switch () {
         case :
         case :
         case :
             return Arrays.equals((byte[]) , (byte[])other.value);
         }
         
         return false;
 	}

Returns the hash code value for this DmtData instance. The hash code is calculated based on the data (selected by the format) of this object.

Returns:
the hash code value for this object
 
 	public int hashCode() {
 		if ( == null)
 			return 42;
 		else
 			return .hashCode();
 	}
 
 	private static void checkDateFormat(String value) {
 		if (value.length() != 8)
 			throw new IllegalArgumentException("Date string '" + value
 					+ "' does not follow the format 'CCYYMMDD'.");
 
 		int year = checkNumber(value"Date", 0, 4, 0, 9999);
 		int month = checkNumber(value"Date", 4, 2, 1, 12);
 		int day = checkNumber(value"Date", 6, 2, 1, 31);
 
 		// Date checking is not prepared for all special rules (for example
 		// historical leap years), production code could contain a full check.
 
 		// Day 31 is invalid for April, June, September and November
 		if ((month == 4 || month == 6 || month == 9 || month == 11)
 				&& day == 31)
 			throw new IllegalArgumentException("Date string '" + value
 					+ "' contains an invalid date.");
 
 		// February 29 is invalid except for leap years, Feb. 30-31 are invalid
 		if (month == 2
 				&& day > 28
 				&& !(day == 29 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)))
 			throw new IllegalArgumentException("Date string '" + value
 					+ "' contains an invalid date.");
 	}
 
 	private static void checkTimeFormat(String value) {
 		if (value.length() > 0 && value.charAt(value.length() - 1) == 'Z')
 			value = value.substring(0, value.length() - 1);
 
 		if (value.length() != 6)
 			throw new IllegalArgumentException("Time string '" + value
 					+ "' does not follow the format 'hhmmss' or 'hhmmssZ'.");
 
 		// Time checking is not prepared for all special rules (for example
 		// leap seconds), production code could contain a full check.
 
 		// if hour is 24, only 240000 should be allowed
 		checkNumber(value"Time", 0, 2, 0, 24);
 		checkNumber(value"Time", 2, 2, 0, 59);
 		checkNumber(value"Time", 4, 2, 0, 59);
 
 		if (value.startsWith("24") && !value.startsWith("240000"))
 			throw new IllegalArgumentException("Time string is out of range.");
 	}
 
 	private static int checkNumber(String valueString nameint from,
 			int lengthint minint max) {
 		String part = value.substring(fromfrom + length);
 		int number;
 		try {
 			number = Integer.parseInt(part);
 		}
 		catch (NumberFormatException e) {
 			throw new IllegalArgumentException(name + " string '" + value
 					+ "' contains a non-numeric part.");
 		}
 		if (number < min || number > max)
 			throw new IllegalArgumentException("A segment of the " + name
 					+ " string '" + value + "' is out of range.");
 
 		return number;
 	}
 
 	// character array of hexadecimal digits, used for printing binary data
 	private static char[]	hex"0123456789ABCDEF".toCharArray();
 
 	// generates a hexadecimal dump of the given binary data
 	private static String getHexDump(byte[] bytes) {
 		if (bytes.length == 0)
 			return "";
 
 		StringBuffer buf = new StringBuffer();
 		String del = "";
 		for (int i = 0; i < bytes.lengthi++) {
 			appendHexByte(buf.append(del), bytes[i]);
 			del = " ";
 		}
 
 		return buf.toString();
 	}
 
 	private static void appendHexByte(StringBuffer bufbyte b) {
 		buf.append([(b & 0xF0) >> 4]).append([b & 0x0F]);
 	}
	private static String getFormatName(int format) {
		return (String.get(new Integer(format));
New to GrepCode? Check out our FAQ X