code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.openmbean;
// java import
//
import java.util.Arrays;
import java.util.HashSet;
import javax.management.Descriptor;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
/** {@collect.stats}
* The {@code OpenMBeanInfoSupport} class describes the management
* information of an <i>open MBean</i>: it is a subclass of {@link
* javax.management.MBeanInfo}, and it implements the {@link
* OpenMBeanInfo} interface. Note that an <i>open MBean</i> is
* recognized as such if its {@code getMBeanInfo()} method returns an
* instance of a class which implements the OpenMBeanInfo interface,
* typically {@code OpenMBeanInfoSupport}.
*
*
* @since 1.5
*/
public class OpenMBeanInfoSupport
extends MBeanInfo
implements OpenMBeanInfo {
/* Serial version */
static final long serialVersionUID = 4349395935420511492L;
// As this instance is immutable, these two values
// need only be calculated once.
private transient Integer myHashCode = null;
private transient String myToString = null;
/** {@collect.stats}
* <p>Constructs an {@code OpenMBeanInfoSupport} instance, which
* describes a class of open MBeans with the specified {@code
* className}, {@code description}, {@code openAttributes}, {@code
* openConstructors} , {@code openOperations} and {@code
* notifications}.</p>
*
* <p>The {@code openAttributes}, {@code openConstructors},
* {@code openOperations} and {@code notifications}
* array parameters are internally copied, so that subsequent changes
* to the arrays referenced by these parameters have no effect on this
* instance.</p>
*
* @param className The fully qualified Java class name of the
* open MBean described by this <CODE>OpenMBeanInfoSupport</CODE>
* instance.
*
* @param description A human readable description of the open
* MBean described by this <CODE>OpenMBeanInfoSupport</CODE>
* instance.
*
* @param openAttributes The list of exposed attributes of the
* described open MBean; Must be an array of instances of a
* subclass of {@code MBeanAttributeInfo}, typically {@code
* OpenMBeanAttributeInfoSupport}.
*
* @param openConstructors The list of exposed public constructors
* of the described open MBean; Must be an array of instances of a
* subclass of {@code MBeanConstructorInfo}, typically {@code
* OpenMBeanConstructorInfoSupport}.
*
* @param openOperations The list of exposed operations of the
* described open MBean. Must be an array of instances of a
* subclass of {@code MBeanOperationInfo}, typically {@code
* OpenMBeanOperationInfoSupport}.
*
* @param notifications The list of notifications emitted by the
* described open MBean.
*
* @throws ArrayStoreException If {@code openAttributes}, {@code
* openConstructors} or {@code openOperations} is not an array of
* instances of a subclass of {@code MBeanAttributeInfo}, {@code
* MBeanConstructorInfo} or {@code MBeanOperationInfo}
* respectively.
*/
public OpenMBeanInfoSupport(String className,
String description,
OpenMBeanAttributeInfo[] openAttributes,
OpenMBeanConstructorInfo[] openConstructors,
OpenMBeanOperationInfo[] openOperations,
MBeanNotificationInfo[] notifications) {
this(className, description,
openAttributes, openConstructors, openOperations, notifications,
(Descriptor) null);
}
/** {@collect.stats}
* <p>Constructs an {@code OpenMBeanInfoSupport} instance, which
* describes a class of open MBeans with the specified {@code
* className}, {@code description}, {@code openAttributes}, {@code
* openConstructors} , {@code openOperations}, {@code
* notifications}, and {@code descriptor}.</p>
*
* <p>The {@code openAttributes}, {@code openConstructors}, {@code
* openOperations} and {@code notifications} array parameters are
* internally copied, so that subsequent changes to the arrays
* referenced by these parameters have no effect on this
* instance.</p>
*
* @param className The fully qualified Java class name of the
* open MBean described by this <CODE>OpenMBeanInfoSupport</CODE>
* instance.
*
* @param description A human readable description of the open
* MBean described by this <CODE>OpenMBeanInfoSupport</CODE>
* instance.
*
* @param openAttributes The list of exposed attributes of the
* described open MBean; Must be an array of instances of a
* subclass of {@code MBeanAttributeInfo}, typically {@code
* OpenMBeanAttributeInfoSupport}.
*
* @param openConstructors The list of exposed public constructors
* of the described open MBean; Must be an array of instances of a
* subclass of {@code MBeanConstructorInfo}, typically {@code
* OpenMBeanConstructorInfoSupport}.
*
* @param openOperations The list of exposed operations of the
* described open MBean. Must be an array of instances of a
* subclass of {@code MBeanOperationInfo}, typically {@code
* OpenMBeanOperationInfoSupport}.
*
* @param notifications The list of notifications emitted by the
* described open MBean.
*
* @param descriptor The descriptor for the MBean. This may be null
* which is equivalent to an empty descriptor.
*
* @throws ArrayStoreException If {@code openAttributes}, {@code
* openConstructors} or {@code openOperations} is not an array of
* instances of a subclass of {@code MBeanAttributeInfo}, {@code
* MBeanConstructorInfo} or {@code MBeanOperationInfo}
* respectively.
*
* @since 1.6
*/
public OpenMBeanInfoSupport(String className,
String description,
OpenMBeanAttributeInfo[] openAttributes,
OpenMBeanConstructorInfo[] openConstructors,
OpenMBeanOperationInfo[] openOperations,
MBeanNotificationInfo[] notifications,
Descriptor descriptor) {
super(className,
description,
attributeArray(openAttributes),
constructorArray(openConstructors),
operationArray(openOperations),
(notifications == null) ? null : notifications.clone(),
descriptor);
}
private static MBeanAttributeInfo[]
attributeArray(OpenMBeanAttributeInfo[] src) {
if (src == null)
return null;
MBeanAttributeInfo[] dst = new MBeanAttributeInfo[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
// may throw an ArrayStoreException
return dst;
}
private static MBeanConstructorInfo[]
constructorArray(OpenMBeanConstructorInfo[] src) {
if (src == null)
return null;
MBeanConstructorInfo[] dst = new MBeanConstructorInfo[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
// may throw an ArrayStoreException
return dst;
}
private static MBeanOperationInfo[]
operationArray(OpenMBeanOperationInfo[] src) {
if (src == null)
return null;
MBeanOperationInfo[] dst = new MBeanOperationInfo[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
return dst;
}
/* *** Commodity methods from java.lang.Object *** */
/** {@collect.stats}
* <p>Compares the specified {@code obj} parameter with this
* {@code OpenMBeanInfoSupport} instance for equality.</p>
*
* <p>Returns {@code true} if and only if all of the following
* statements are true:
*
* <ul>
* <li>{@code obj} is non null,</li>
* <li>{@code obj} also implements the {@code OpenMBeanInfo}
* interface,</li>
* <li>their class names are equal</li>
* <li>their infos on attributes, constructors, operations and
* notifications are equal</li>
* </ul>
*
* This ensures that this {@code equals} method works properly for
* {@code obj} parameters which are different implementations of
* the {@code OpenMBeanInfo} interface.
*
* @param obj the object to be compared for equality with this
* {@code OpenMBeanInfoSupport} instance;
*
* @return {@code true} if the specified object is equal to this
* {@code OpenMBeanInfoSupport} instance.
*/
public boolean equals(Object obj) {
// if obj is null, return false
//
if (obj == null) {
return false;
}
// if obj is not a OpenMBeanInfo, return false
//
OpenMBeanInfo other;
try {
other = (OpenMBeanInfo) obj;
} catch (ClassCastException e) {
return false;
}
// Now, really test for equality between this OpenMBeanInfo
// implementation and the other:
//
// their MBean className should be equal
if ( ! this.getClassName().equals(other.getClassName()) )
return false;
// their infos on attributes should be equal (order not
// significant => equality between sets, not arrays or lists)
if (!sameArrayContents(this.getAttributes(), other.getAttributes()))
return false;
// their infos on constructors should be equal (order not
// significant => equality between sets, not arrays or lists)
if (!sameArrayContents(this.getConstructors(), other.getConstructors()))
return false;
// their infos on operations should be equal (order not
// significant => equality between sets, not arrays or lists)
if (!sameArrayContents(this.getOperations(), other.getOperations()))
return false;
// their infos on notifications should be equal (order not
// significant => equality between sets, not arrays or lists)
if (!sameArrayContents(this.getNotifications(), other.getNotifications()))
return false;
// All tests for equality were successful
//
return true;
}
private static <T> boolean sameArrayContents(T[] a1, T[] a2) {
return (new HashSet<T>(Arrays.asList(a1))
.equals(new HashSet<T>(Arrays.asList(a2))));
}
/** {@collect.stats}
* <p>Returns the hash code value for this {@code
* OpenMBeanInfoSupport} instance.</p>
*
* <p>The hash code of an {@code OpenMBeanInfoSupport} instance is
* the sum of the hash codes of all elements of information used
* in {@code equals} comparisons (ie: its class name, and its
* infos on attributes, constructors, operations and
* notifications, where the hashCode of each of these arrays is
* calculated by a call to {@code new
* java.util.HashSet(java.util.Arrays.asList(this.getSignature)).hashCode()}).</p>
*
* <p>This ensures that {@code t1.equals(t2)} implies that {@code
* t1.hashCode()==t2.hashCode()} for any two {@code
* OpenMBeanInfoSupport} instances {@code t1} and {@code t2}, as
* required by the general contract of the method {@link
* Object#hashCode() Object.hashCode()}.</p>
*
* <p>However, note that another instance of a class implementing
* the {@code OpenMBeanInfo} interface may be equal to this {@code
* OpenMBeanInfoSupport} instance as defined by {@link
* #equals(java.lang.Object)}, but may have a different hash code
* if it is calculated differently.</p>
*
* <p>As {@code OpenMBeanInfoSupport} instances are immutable, the
* hash code for this instance is calculated once, on the first
* call to {@code hashCode}, and then the same value is returned
* for subsequent calls.</p>
*
* @return the hash code value for this {@code
* OpenMBeanInfoSupport} instance
*/
public int hashCode() {
// Calculate the hash code value if it has not yet been done
// (ie 1st call to hashCode())
//
if (myHashCode == null) {
int value = 0;
value += this.getClassName().hashCode();
value += arraySetHash(this.getAttributes());
value += arraySetHash(this.getConstructors());
value += arraySetHash(this.getOperations());
value += arraySetHash(this.getNotifications());
myHashCode = new Integer(value);
}
// return always the same hash code for this instance (immutable)
//
return myHashCode.intValue();
}
private static <T> int arraySetHash(T[] a) {
return new HashSet<T>(Arrays.asList(a)).hashCode();
}
/** {@collect.stats}
* <p>Returns a string representation of this {@code
* OpenMBeanInfoSupport} instance.</p>
*
* <p>The string representation consists of the name of this class
* (ie {@code javax.management.openmbean.OpenMBeanInfoSupport}),
* the MBean class name, the string representation of infos on
* attributes, constructors, operations and notifications of the
* described MBean and the string representation of the descriptor.</p>
*
* <p>As {@code OpenMBeanInfoSupport} instances are immutable, the
* string representation for this instance is calculated once, on
* the first call to {@code toString}, and then the same value is
* returned for subsequent calls.</p>
*
* @return a string representation of this {@code
* OpenMBeanInfoSupport} instance
*/
public String toString() {
// Calculate the string value if it has not yet been done (ie
// 1st call to toString())
//
if (myToString == null) {
myToString = new StringBuilder()
.append(this.getClass().getName())
.append("(mbean_class_name=")
.append(this.getClassName())
.append(",attributes=")
.append(Arrays.asList(this.getAttributes()).toString())
.append(",constructors=")
.append(Arrays.asList(this.getConstructors()).toString())
.append(",operations=")
.append(Arrays.asList(this.getOperations()).toString())
.append(",notifications=")
.append(Arrays.asList(this.getNotifications()).toString())
.append(",descriptor=")
.append(this.getDescriptor())
.append(")")
.toString();
}
// return always the same string representation for this
// instance (immutable)
//
return myToString;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.openmbean;
/** {@collect.stats}
* This runtime exception is thrown to indicate that a method parameter which was expected to be
* an item name of a <i>composite data</i> or a row index of a <i>tabular data</i> is not valid.
*
*
* @since 1.5
*/
public class InvalidKeyException extends IllegalArgumentException {
private static final long serialVersionUID = 4224269443946322062L;
/** {@collect.stats}
* An InvalidKeyException with no detail message.
*/
public InvalidKeyException() {
super();
}
/** {@collect.stats}
* An InvalidKeyException with a detail message.
*
* @param msg the detail message.
*/
public InvalidKeyException(String msg) {
super(msg);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
// jmx imports
//
import javax.management.ObjectName;
/** {@collect.stats}
* Provides definitions of the notifications sent by monitor MBeans.
* <P>
* The notification source and a set of parameters concerning the monitor MBean's state
* need to be specified when creating a new object of this class.
*
* The list of notifications fired by the monitor MBeans is the following:
*
* <UL>
* <LI>Common to all kind of monitors:
* <UL>
* <LI>The observed object is not registered in the MBean server.
* <LI>The observed attribute is not contained in the observed object.
* <LI>The type of the observed attribute is not correct.
* <LI>Any exception (except the cases described above) occurs when trying to get the value of the observed attribute.
* </UL>
* <LI>Common to the counter and the gauge monitors:
* <UL>
* <LI>The threshold high or threshold low are not of the same type as the gauge (gauge monitors).
* <LI>The threshold or the offset or the modulus are not of the same type as the counter (counter monitors).
* </UL>
* <LI>Counter monitors only:
* <UL>
* <LI>The observed attribute has reached the threshold value.
* </UL>
* <LI>Gauge monitors only:
* <UL>
* <LI>The observed attribute has exceeded the threshold high value.
* <LI>The observed attribute has exceeded the threshold low value.
* </UL>
* <LI>String monitors only:
* <UL>
* <LI>The observed attribute has matched the "string to compare" value.
* <LI>The observed attribute has differed from the "string to compare" value.
* </UL>
* </UL>
*
*
* @since 1.5
*/
public class MonitorNotification extends javax.management.Notification {
/*
* ------------------------------------------
* PUBLIC VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Notification type denoting that the observed object is not registered in the MBean server.
* This notification is fired by all kinds of monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.error.mbean</CODE>.
*/
public static final String OBSERVED_OBJECT_ERROR = "jmx.monitor.error.mbean";
/** {@collect.stats}
* Notification type denoting that the observed attribute is not contained in the observed object.
* This notification is fired by all kinds of monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.error.attribute</CODE>.
*/
public static final String OBSERVED_ATTRIBUTE_ERROR = "jmx.monitor.error.attribute";
/** {@collect.stats}
* Notification type denoting that the type of the observed attribute is not correct.
* This notification is fired by all kinds of monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.error.type</CODE>.
*/
public static final String OBSERVED_ATTRIBUTE_TYPE_ERROR = "jmx.monitor.error.type";
/** {@collect.stats}
* Notification type denoting that the type of the thresholds, offset or modulus is not correct.
* This notification is fired by counter and gauge monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.error.threshold</CODE>.
*/
public static final String THRESHOLD_ERROR = "jmx.monitor.error.threshold";
/** {@collect.stats}
* Notification type denoting that a non-predefined error type has occurred when trying to get the value of the observed attribute.
* This notification is fired by all kinds of monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.error.runtime</CODE>.
*/
public static final String RUNTIME_ERROR = "jmx.monitor.error.runtime";
/** {@collect.stats}
* Notification type denoting that the observed attribute has reached the threshold value.
* This notification is only fired by counter monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.counter.threshold</CODE>.
*/
public static final String THRESHOLD_VALUE_EXCEEDED = "jmx.monitor.counter.threshold";
/** {@collect.stats}
* Notification type denoting that the observed attribute has exceeded the threshold high value.
* This notification is only fired by gauge monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.gauge.high</CODE>.
*/
public static final String THRESHOLD_HIGH_VALUE_EXCEEDED = "jmx.monitor.gauge.high";
/** {@collect.stats}
* Notification type denoting that the observed attribute has exceeded the threshold low value.
* This notification is only fired by gauge monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.gauge.low</CODE>.
*/
public static final String THRESHOLD_LOW_VALUE_EXCEEDED = "jmx.monitor.gauge.low";
/** {@collect.stats}
* Notification type denoting that the observed attribute has matched the "string to compare" value.
* This notification is only fired by string monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.string.matches</CODE>.
*/
public static final String STRING_TO_COMPARE_VALUE_MATCHED = "jmx.monitor.string.matches";
/** {@collect.stats}
* Notification type denoting that the observed attribute has differed from the "string to compare" value.
* This notification is only fired by string monitors.
* <BR>The value of this notification type is <CODE>jmx.monitor.string.differs</CODE>.
*/
public static final String STRING_TO_COMPARE_VALUE_DIFFERED = "jmx.monitor.string.differs";
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/* Serial version */
private static final long serialVersionUID = -4608189663661929204L;
/** {@collect.stats}
* @serial Monitor notification observed object.
*/
private ObjectName observedObject = null;
/** {@collect.stats}
* @serial Monitor notification observed attribute.
*/
private String observedAttribute = null;
/** {@collect.stats}
* @serial Monitor notification derived gauge.
*/
private Object derivedGauge = null;
/** {@collect.stats}
* @serial Monitor notification release mechanism.
* This value is used to keep the threshold/string (depending on the
* monitor type) that triggered off this notification.
*/
private Object trigger = null;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Creates a monitor notification object.
*
* @param type The notification type.
* @param source The notification producer.
* @param sequenceNumber The notification sequence number within the source object.
* @param timeStamp The notification emission date.
* @param msg The notification message.
* @param obsObj The object observed by the producer of this notification.
* @param obsAtt The attribute observed by the producer of this notification.
* @param derGauge The derived gauge.
* @param trigger The threshold/string (depending on the monitor type) that triggered the notification.
*/
MonitorNotification(String type, Object source, long sequenceNumber, long timeStamp, String msg,
ObjectName obsObj, String obsAtt, Object derGauge, Object trigger) {
super(type, source, sequenceNumber, timeStamp, msg);
this.observedObject = obsObj;
this.observedAttribute = obsAtt;
this.derivedGauge = derGauge;
this.trigger = trigger;
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the observed object of this monitor notification.
*
* @return The observed object.
*/
public ObjectName getObservedObject() {
return observedObject;
}
/** {@collect.stats}
* Gets the observed attribute of this monitor notification.
*
* @return The observed attribute.
*/
public String getObservedAttribute() {
return observedAttribute;
}
/** {@collect.stats}
* Gets the derived gauge of this monitor notification.
*
* @return The derived gauge.
*/
public Object getDerivedGauge() {
return derivedGauge;
}
/** {@collect.stats}
* Gets the threshold/string (depending on the monitor type) that triggered off this monitor notification.
*
* @return The trigger.
*/
public Object getTrigger() {
return trigger;
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
// jmx imports
//
import javax.management.ObjectName;
/** {@collect.stats}
* Exposes the remote management interface of the counter monitor MBean.
*
*
* @since 1.5
*/
public interface CounterMonitorMBean extends MonitorMBean {
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge.
*
* @return The derived gauge.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public Number getDerivedGauge();
/** {@collect.stats}
* Gets the derived gauge timestamp.
*
* @return The derived gauge timestamp.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public long getDerivedGaugeTimeStamp();
/** {@collect.stats}
* Gets the threshold value.
*
* @return The threshold value.
*
* @see #setThreshold(Number)
*
* @deprecated As of JMX 1.2, replaced by {@link #getThreshold(ObjectName)}
*/
@Deprecated
public Number getThreshold();
/** {@collect.stats}
* Sets the threshold value.
*
* @see #getThreshold()
*
* @param value The threshold value.
* @exception java.lang.IllegalArgumentException The specified threshold is null or the threshold value is less than zero.
* @deprecated As of JMX 1.2, replaced by {@link #setInitThreshold}
*/
@Deprecated
public void setThreshold(Number value) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the derived gauge for the specified MBean.
*
* @param object the MBean for which the derived gauge is to be returned
* @return The derived gauge for the specified MBean if this MBean is in the
* set of observed MBeans, or <code>null</code> otherwise.
*
*/
public Number getDerivedGauge(ObjectName object);
/** {@collect.stats}
* Gets the derived gauge timestamp for the specified MBean.
*
* @param object the MBean for which the derived gauge timestamp is to be returned
* @return The derived gauge timestamp for the specified MBean if this MBean
* is in the set of observed MBeans, or <code>null</code> otherwise.
*
*/
public long getDerivedGaugeTimeStamp(ObjectName object);
/** {@collect.stats}
* Gets the threshold value for the specified MBean.
*
* @param object the MBean for which the threshold value is to be returned
* @return The threshold value for the specified MBean if this MBean
* is in the set of observed MBeans, or <code>null</code> otherwise.
*
* @see #setThreshold
*
*/
public Number getThreshold(ObjectName object);
/** {@collect.stats}
* Gets the initial threshold value common to all observed objects.
*
* @return The initial threshold value.
*
* @see #setInitThreshold
*
*/
public Number getInitThreshold();
/** {@collect.stats}
* Sets the initial threshold value common to all observed MBeans.
*
* @param value The initial threshold value.
* @exception java.lang.IllegalArgumentException The specified
* threshold is null or the threshold value is less than zero.
*
* @see #getInitThreshold
*
*/
public void setInitThreshold(Number value) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the offset value.
*
* @see #setOffset(Number)
*
* @return The offset value.
*/
public Number getOffset();
/** {@collect.stats}
* Sets the offset value.
*
* @param value The offset value.
* @exception java.lang.IllegalArgumentException The specified
* offset is null or the offset value is less than zero.
*
* @see #getOffset()
*/
public void setOffset(Number value) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the modulus value.
*
* @return The modulus value.
*
* @see #setModulus
*/
public Number getModulus();
/** {@collect.stats}
* Sets the modulus value.
*
* @param value The modulus value.
* @exception java.lang.IllegalArgumentException The specified
* modulus is null or the modulus value is less than zero.
*
* @see #getModulus
*/
public void setModulus(Number value) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the notification's on/off switch value.
*
* @return <CODE>true</CODE> if the counter monitor notifies when
* exceeding the threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotify
*/
public boolean getNotify();
/** {@collect.stats}
* Sets the notification's on/off switch value.
*
* @param value The notification's on/off switch value.
*
* @see #getNotify
*/
public void setNotify(boolean value);
/** {@collect.stats}
* Gets the difference mode flag value.
*
* @return <CODE>true</CODE> if the difference mode is used,
* <CODE>false</CODE> otherwise.
*
* @see #setDifferenceMode
*/
public boolean getDifferenceMode();
/** {@collect.stats}
* Sets the difference mode flag value.
*
* @param value The difference mode flag value.
*
* @see #getDifferenceMode
*/
public void setDifferenceMode(boolean value);
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
import static com.sun.jmx.defaults.JmxProperties.MONITOR_LOGGER;
import java.util.logging.Level;
import javax.management.ObjectName;
import javax.management.MBeanNotificationInfo;
import static javax.management.monitor.Monitor.NumericalType.*;
import static javax.management.monitor.MonitorNotification.*;
/** {@collect.stats}
* Defines a monitor MBean designed to observe the values of a counter
* attribute.
*
* <P> A counter monitor sends a {@link
* MonitorNotification#THRESHOLD_VALUE_EXCEEDED threshold
* notification} when the value of the counter reaches or exceeds a
* threshold known as the comparison level. The notify flag must be
* set to <CODE>true</CODE>.
*
* <P> In addition, an offset mechanism enables particular counting
* intervals to be detected. If the offset value is not zero,
* whenever the threshold is triggered by the counter value reaching a
* comparison level, that comparison level is incremented by the
* offset value. This is regarded as taking place instantaneously,
* that is, before the count is incremented. Thus, for each level,
* the threshold triggers an event notification every time the count
* increases by an interval equal to the offset value.
*
* <P> If the counter can wrap around its maximum value, the modulus
* needs to be specified. The modulus is the value at which the
* counter is reset to zero.
*
* <P> If the counter difference mode is used, the value of the
* derived gauge is calculated as the difference between the observed
* counter values for two successive observations. If this difference
* is negative, the value of the derived gauge is incremented by the
* value of the modulus. The derived gauge value (V[t]) is calculated
* using the following method:
*
* <UL>
* <LI>if (counter[t] - counter[t-GP]) is positive then
* V[t] = counter[t] - counter[t-GP]
* <LI>if (counter[t] - counter[t-GP]) is negative then
* V[t] = counter[t] - counter[t-GP] + MODULUS
* </UL>
*
* This implementation of the counter monitor requires the observed
* attribute to be of the type integer (<CODE>Byte</CODE>,
* <CODE>Integer</CODE>, <CODE>Short</CODE>, <CODE>Long</CODE>).
*
*
* @since 1.5
*/
public class CounterMonitor extends Monitor implements CounterMonitorMBean {
/*
* ------------------------------------------
* PACKAGE CLASSES
* ------------------------------------------
*/
static class CounterMonitorObservedObject extends ObservedObject {
public CounterMonitorObservedObject(ObjectName observedObject) {
super(observedObject);
}
public final synchronized Number getThreshold() {
return threshold;
}
public final synchronized void setThreshold(Number threshold) {
this.threshold = threshold;
}
public final synchronized Number getPreviousScanCounter() {
return previousScanCounter;
}
public final synchronized void setPreviousScanCounter(
Number previousScanCounter) {
this.previousScanCounter = previousScanCounter;
}
public final synchronized boolean getModulusExceeded() {
return modulusExceeded;
}
public final synchronized void setModulusExceeded(
boolean modulusExceeded) {
this.modulusExceeded = modulusExceeded;
}
public final synchronized Number getDerivedGaugeExceeded() {
return derivedGaugeExceeded;
}
public final synchronized void setDerivedGaugeExceeded(
Number derivedGaugeExceeded) {
this.derivedGaugeExceeded = derivedGaugeExceeded;
}
public final synchronized boolean getDerivedGaugeValid() {
return derivedGaugeValid;
}
public final synchronized void setDerivedGaugeValid(
boolean derivedGaugeValid) {
this.derivedGaugeValid = derivedGaugeValid;
}
public final synchronized boolean getEventAlreadyNotified() {
return eventAlreadyNotified;
}
public final synchronized void setEventAlreadyNotified(
boolean eventAlreadyNotified) {
this.eventAlreadyNotified = eventAlreadyNotified;
}
public final synchronized NumericalType getType() {
return type;
}
public final synchronized void setType(NumericalType type) {
this.type = type;
}
private Number threshold;
private Number previousScanCounter;
private boolean modulusExceeded;
private Number derivedGaugeExceeded;
private boolean derivedGaugeValid;
private boolean eventAlreadyNotified;
private NumericalType type;
}
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Counter modulus.
* <BR>The default value is a null Integer object.
*/
private Number modulus = INTEGER_ZERO;
/** {@collect.stats}
* Counter offset.
* <BR>The default value is a null Integer object.
*/
private Number offset = INTEGER_ZERO;
/** {@collect.stats}
* Flag indicating if the counter monitor notifies when exceeding
* the threshold. The default value is set to
* <CODE>false</CODE>.
*/
private boolean notify = false;
/** {@collect.stats}
* Flag indicating if the counter difference mode is used. If the
* counter difference mode is used, the derived gauge is the
* difference between two consecutive observed values. Otherwise,
* the derived gauge is directly the value of the observed
* attribute. The default value is set to <CODE>false</CODE>.
*/
private boolean differenceMode = false;
/** {@collect.stats}
* Initial counter threshold. This value is used to initialize
* the threshold when a new object is added to the list and reset
* the threshold to its initial value each time the counter
* resets.
*/
private Number initThreshold = INTEGER_ZERO;
private static final String[] types = {
RUNTIME_ERROR,
OBSERVED_OBJECT_ERROR,
OBSERVED_ATTRIBUTE_ERROR,
OBSERVED_ATTRIBUTE_TYPE_ERROR,
THRESHOLD_ERROR,
THRESHOLD_VALUE_EXCEEDED
};
private static final MBeanNotificationInfo[] notifsInfo = {
new MBeanNotificationInfo(
types,
"javax.management.monitor.MonitorNotification",
"Notifications sent by the CounterMonitor MBean")
};
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Default constructor.
*/
public CounterMonitor() {
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Starts the counter monitor.
*/
public synchronized void start() {
if (isActive()) {
MONITOR_LOGGER.logp(Level.FINER, CounterMonitor.class.getName(),
"start", "the monitor is already active");
return;
}
// Reset values.
//
for (ObservedObject o : observedObjects) {
final CounterMonitorObservedObject cmo =
(CounterMonitorObservedObject) o;
cmo.setThreshold(initThreshold);
cmo.setModulusExceeded(false);
cmo.setEventAlreadyNotified(false);
cmo.setPreviousScanCounter(null);
}
doStart();
}
/** {@collect.stats}
* Stops the counter monitor.
*/
public synchronized void stop() {
doStop();
}
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge of the specified object, if this object is
* contained in the set of observed MBeans, or <code>null</code> otherwise.
*
* @param object the name of the object whose derived gauge is to
* be returned.
*
* @return The derived gauge of the specified object.
*
*/
@Override
public synchronized Number getDerivedGauge(ObjectName object) {
return (Number) super.getDerivedGauge(object);
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the specified object, if
* this object is contained in the set of observed MBeans, or
* <code>0</code> otherwise.
*
* @param object the name of the object whose derived gauge
* timestamp is to be returned.
*
* @return The derived gauge timestamp of the specified object.
*
*/
@Override
public synchronized long getDerivedGaugeTimeStamp(ObjectName object) {
return super.getDerivedGaugeTimeStamp(object);
}
/** {@collect.stats}
* Gets the current threshold value of the specified object, if
* this object is contained in the set of observed MBeans, or
* <code>null</code> otherwise.
*
* @param object the name of the object whose threshold is to be
* returned.
*
* @return The threshold value of the specified object.
*
*/
public synchronized Number getThreshold(ObjectName object) {
final CounterMonitorObservedObject o =
(CounterMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// If the counter that is monitored rolls over when it reaches a
// maximum value, then the modulus value needs to be set to that
// maximum value. The threshold will then also roll over whenever
// it strictly exceeds the modulus value. When the threshold rolls
// over, it is reset to the value that was specified through the
// latest call to the monitor's setInitThreshold method, before
// any offsets were applied.
//
if (offset.longValue() > 0L &&
modulus.longValue() > 0L &&
o.getThreshold().longValue() > modulus.longValue()) {
return initThreshold;
} else {
return o.getThreshold();
}
}
/** {@collect.stats}
* Gets the initial threshold value common to all observed objects.
*
* @return The initial threshold.
*
* @see #setInitThreshold
*
*/
public synchronized Number getInitThreshold() {
return initThreshold;
}
/** {@collect.stats}
* Sets the initial threshold value common to all observed objects.
*
* <BR>The current threshold of every object in the set of
* observed MBeans is updated consequently.
*
* @param value The initial threshold value.
*
* @exception IllegalArgumentException The specified
* threshold is null or the threshold value is less than zero.
*
* @see #getInitThreshold
*
*/
public synchronized void setInitThreshold(Number value)
throws IllegalArgumentException {
if (value == null) {
throw new IllegalArgumentException("Null threshold");
}
if (value.longValue() < 0L) {
throw new IllegalArgumentException("Negative threshold");
}
if (initThreshold.equals(value))
return;
initThreshold = value;
// Reset values.
//
int index = 0;
for (ObservedObject o : observedObjects) {
resetAlreadyNotified(o, index++, THRESHOLD_ERROR_NOTIFIED);
final CounterMonitorObservedObject cmo =
(CounterMonitorObservedObject) o;
cmo.setThreshold(value);
cmo.setModulusExceeded(false);
cmo.setEventAlreadyNotified(false);
}
}
/** {@collect.stats}
* Returns the derived gauge of the first object in the set of
* observed MBeans.
*
* @return The derived gauge.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public synchronized Number getDerivedGauge() {
if (observedObjects.isEmpty()) {
return null;
} else {
return (Number) observedObjects.get(0).getDerivedGauge();
}
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the first object in the set
* of observed MBeans.
*
* @return The derived gauge timestamp.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public synchronized long getDerivedGaugeTimeStamp() {
if (observedObjects.isEmpty()) {
return 0;
} else {
return observedObjects.get(0).getDerivedGaugeTimeStamp();
}
}
/** {@collect.stats}
* Gets the threshold value of the first object in the set of
* observed MBeans.
*
* @return The threshold value.
*
* @see #setThreshold
*
* @deprecated As of JMX 1.2, replaced by {@link #getThreshold(ObjectName)}
*/
@Deprecated
public synchronized Number getThreshold() {
return getThreshold(getObservedObject());
}
/** {@collect.stats}
* Sets the initial threshold value.
*
* @param value The initial threshold value.
*
* @exception IllegalArgumentException The specified threshold is
* null or the threshold value is less than zero.
*
* @see #getThreshold()
*
* @deprecated As of JMX 1.2, replaced by {@link #setInitThreshold}
*/
@Deprecated
public synchronized void setThreshold(Number value)
throws IllegalArgumentException {
setInitThreshold(value);
}
/** {@collect.stats}
* Gets the offset value common to all observed MBeans.
*
* @return The offset value.
*
* @see #setOffset
*/
public synchronized Number getOffset() {
return offset;
}
/** {@collect.stats}
* Sets the offset value common to all observed MBeans.
*
* @param value The offset value.
*
* @exception IllegalArgumentException The specified
* offset is null or the offset value is less than zero.
*
* @see #getOffset
*/
public synchronized void setOffset(Number value)
throws IllegalArgumentException {
if (value == null) {
throw new IllegalArgumentException("Null offset");
}
if (value.longValue() < 0L) {
throw new IllegalArgumentException("Negative offset");
}
if (offset.equals(value))
return;
offset = value;
int index = 0;
for (ObservedObject o : observedObjects) {
resetAlreadyNotified(o, index++, THRESHOLD_ERROR_NOTIFIED);
}
}
/** {@collect.stats}
* Gets the modulus value common to all observed MBeans.
*
* @see #setModulus
*
* @return The modulus value.
*/
public synchronized Number getModulus() {
return modulus;
}
/** {@collect.stats}
* Sets the modulus value common to all observed MBeans.
*
* @param value The modulus value.
*
* @exception IllegalArgumentException The specified
* modulus is null or the modulus value is less than zero.
*
* @see #getModulus
*/
public synchronized void setModulus(Number value)
throws IllegalArgumentException {
if (value == null) {
throw new IllegalArgumentException("Null modulus");
}
if (value.longValue() < 0L) {
throw new IllegalArgumentException("Negative modulus");
}
if (modulus.equals(value))
return;
modulus = value;
// Reset values.
//
int index = 0;
for (ObservedObject o : observedObjects) {
resetAlreadyNotified(o, index++, THRESHOLD_ERROR_NOTIFIED);
final CounterMonitorObservedObject cmo =
(CounterMonitorObservedObject) o;
cmo.setModulusExceeded(false);
}
}
/** {@collect.stats}
* Gets the notification's on/off switch value common to all
* observed MBeans.
*
* @return <CODE>true</CODE> if the counter monitor notifies when
* exceeding the threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotify
*/
public synchronized boolean getNotify() {
return notify;
}
/** {@collect.stats}
* Sets the notification's on/off switch value common to all
* observed MBeans.
*
* @param value The notification's on/off switch value.
*
* @see #getNotify
*/
public synchronized void setNotify(boolean value) {
if (notify == value)
return;
notify = value;
}
/** {@collect.stats}
* Gets the difference mode flag value common to all observed MBeans.
*
* @return <CODE>true</CODE> if the difference mode is used,
* <CODE>false</CODE> otherwise.
*
* @see #setDifferenceMode
*/
public synchronized boolean getDifferenceMode() {
return differenceMode;
}
/** {@collect.stats}
* Sets the difference mode flag value common to all observed MBeans.
*
* @param value The difference mode flag value.
*
* @see #getDifferenceMode
*/
public synchronized void setDifferenceMode(boolean value) {
if (differenceMode == value)
return;
differenceMode = value;
// Reset values.
//
for (ObservedObject o : observedObjects) {
final CounterMonitorObservedObject cmo =
(CounterMonitorObservedObject) o;
cmo.setThreshold(initThreshold);
cmo.setModulusExceeded(false);
cmo.setEventAlreadyNotified(false);
cmo.setPreviousScanCounter(null);
}
}
/** {@collect.stats}
* Returns a <CODE>NotificationInfo</CODE> object containing the
* name of the Java class of the notification and the notification
* types sent by the counter monitor.
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return notifsInfo.clone();
}
/*
* ------------------------------------------
* PRIVATE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Updates the derived gauge attribute of the observed object.
*
* @param scanCounter The value of the observed attribute.
* @param o The observed object.
* @return <CODE>true</CODE> if the derived gauge value is valid,
* <CODE>false</CODE> otherwise. The derived gauge value is
* invalid when the differenceMode flag is set to
* <CODE>true</CODE> and it is the first notification (so we
* haven't 2 consecutive values to update the derived gauge).
*/
private synchronized boolean updateDerivedGauge(
Object scanCounter, CounterMonitorObservedObject o) {
boolean is_derived_gauge_valid;
// The counter difference mode is used.
//
if (differenceMode) {
// The previous scan counter has been initialized.
//
if (o.getPreviousScanCounter() != null) {
setDerivedGaugeWithDifference((Number)scanCounter, null, o);
// If derived gauge is negative it means that the
// counter has wrapped around and the value of the
// threshold needs to be reset to its initial value.
//
if (((Number)o.getDerivedGauge()).longValue() < 0L) {
if (modulus.longValue() > 0L) {
setDerivedGaugeWithDifference((Number)scanCounter,
modulus, o);
}
o.setThreshold(initThreshold);
o.setEventAlreadyNotified(false);
}
is_derived_gauge_valid = true;
}
// The previous scan counter has not been initialized.
// We cannot update the derived gauge...
//
else {
is_derived_gauge_valid = false;
}
o.setPreviousScanCounter((Number)scanCounter);
}
// The counter difference mode is not used.
//
else {
o.setDerivedGauge((Number)scanCounter);
is_derived_gauge_valid = true;
}
return is_derived_gauge_valid;
}
/** {@collect.stats}
* Updates the notification attribute of the observed object
* and notifies the listeners only once if the notify flag
* is set to <CODE>true</CODE>.
* @param o The observed object.
*/
private synchronized MonitorNotification updateNotifications(
CounterMonitorObservedObject o) {
MonitorNotification n = null;
// Send notification if notify is true.
//
if (!o.getEventAlreadyNotified()) {
if (((Number)o.getDerivedGauge()).longValue() >=
o.getThreshold().longValue()) {
if (notify) {
n = new MonitorNotification(THRESHOLD_VALUE_EXCEEDED,
this,
0,
0,
"",
null,
null,
null,
o.getThreshold());
}
if (!differenceMode) {
o.setEventAlreadyNotified(true);
}
}
} else {
if (MONITOR_LOGGER.isLoggable(Level.FINER)) {
final StringBuilder strb = new StringBuilder()
.append("The notification:")
.append("\n\tNotification observed object = ")
.append(o.getObservedObject())
.append("\n\tNotification observed attribute = ")
.append(getObservedAttribute())
.append("\n\tNotification threshold level = ")
.append(o.getThreshold())
.append("\n\tNotification derived gauge = ")
.append(o.getDerivedGauge())
.append("\nhas already been sent");
MONITOR_LOGGER.logp(Level.FINER, CounterMonitor.class.getName(),
"updateNotifications", strb.toString());
}
}
return n;
}
/** {@collect.stats}
* Updates the threshold attribute of the observed object.
* @param o The observed object.
*/
private synchronized void updateThreshold(CounterMonitorObservedObject o) {
// Calculate the new threshold value if the threshold has been
// exceeded and if the offset value is greater than zero.
//
if (((Number)o.getDerivedGauge()).longValue() >=
o.getThreshold().longValue()) {
if (offset.longValue() > 0L) {
// Increment the threshold until its value is greater
// than the one for the current derived gauge.
//
long threshold_value = o.getThreshold().longValue();
while (((Number)o.getDerivedGauge()).longValue() >=
threshold_value) {
threshold_value += offset.longValue();
}
// Set threshold attribute.
//
switch (o.getType()) {
case INTEGER:
o.setThreshold(new Integer((int)threshold_value));
break;
case BYTE:
o.setThreshold(new Byte((byte)threshold_value));
break;
case SHORT:
o.setThreshold(new Short((short)threshold_value));
break;
case LONG:
o.setThreshold(new Long(threshold_value));
break;
default:
// Should never occur...
MONITOR_LOGGER.logp(Level.FINEST,
CounterMonitor.class.getName(),
"updateThreshold",
"the threshold type is invalid");
break;
}
// If the counter can wrap around when it reaches
// its maximum and we are not dealing with counter
// differences then we need to reset the threshold
// to its initial value too.
//
if (!differenceMode) {
if (modulus.longValue() > 0L) {
if (o.getThreshold().longValue() >
modulus.longValue()) {
o.setModulusExceeded(true);
o.setDerivedGaugeExceeded(
(Number) o.getDerivedGauge());
}
}
}
// Threshold value has been modified so we can notify again.
//
o.setEventAlreadyNotified(false);
} else {
o.setModulusExceeded(true);
o.setDerivedGaugeExceeded((Number) o.getDerivedGauge());
}
}
}
/** {@collect.stats}
* Sets the derived gauge of the specified observed object when the
* differenceMode flag is set to <CODE>true</CODE>. Integer types
* only are allowed.
*
* @param scanCounter The value of the observed attribute.
* @param mod The counter modulus value.
* @param o The observed object.
*/
private synchronized void setDerivedGaugeWithDifference(
Number scanCounter, Number mod, CounterMonitorObservedObject o) {
/* We do the arithmetic using longs here even though the
result may end up in a smaller type. Since
l == (byte)l (mod 256) for any long l,
(byte) ((byte)l1 + (byte)l2) == (byte) (l1 + l2),
and likewise for subtraction. So it's the same as if
we had done the arithmetic in the smaller type.*/
long derived =
scanCounter.longValue() - o.getPreviousScanCounter().longValue();
if (mod != null)
derived += modulus.longValue();
switch (o.getType()) {
case INTEGER: o.setDerivedGauge(new Integer((int) derived)); break;
case BYTE: o.setDerivedGauge(new Byte((byte) derived)); break;
case SHORT: o.setDerivedGauge(new Short((short) derived)); break;
case LONG: o.setDerivedGauge(new Long(derived)); break;
default:
// Should never occur...
MONITOR_LOGGER.logp(Level.FINEST, CounterMonitor.class.getName(),
"setDerivedGaugeWithDifference",
"the threshold type is invalid");
break;
}
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Factory method for ObservedObject creation.
*
* @since 1.6
*/
@Override
ObservedObject createObservedObject(ObjectName object) {
final CounterMonitorObservedObject cmo =
new CounterMonitorObservedObject(object);
cmo.setThreshold(initThreshold);
cmo.setModulusExceeded(false);
cmo.setEventAlreadyNotified(false);
cmo.setPreviousScanCounter(null);
return cmo;
}
/** {@collect.stats}
* This method globally sets the derived gauge type for the given
* "object" and "attribute" after checking that the type of the
* supplied observed attribute value is one of the value types
* supported by this monitor.
*/
@Override
synchronized boolean isComparableTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
final CounterMonitorObservedObject o =
(CounterMonitorObservedObject) getObservedObject(object);
if (o == null)
return false;
// Check that the observed attribute is of type "Integer".
//
if (value instanceof Integer) {
o.setType(INTEGER);
} else if (value instanceof Byte) {
o.setType(BYTE);
} else if (value instanceof Short) {
o.setType(SHORT);
} else if (value instanceof Long) {
o.setType(LONG);
} else {
return false;
}
return true;
}
@Override
synchronized Comparable<?> getDerivedGaugeFromComparable(
ObjectName object,
String attribute,
Comparable<?> value) {
final CounterMonitorObservedObject o =
(CounterMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// Check if counter has wrapped around.
//
if (o.getModulusExceeded()) {
if (((Number)o.getDerivedGauge()).longValue() <
o.getDerivedGaugeExceeded().longValue()) {
o.setThreshold(initThreshold);
o.setModulusExceeded(false);
o.setEventAlreadyNotified(false);
}
}
// Update the derived gauge attributes and check the
// validity of the new value. The derived gauge value
// is invalid when the differenceMode flag is set to
// true and it is the first notification, i.e. we
// haven't got 2 consecutive values to update the
// derived gauge.
//
o.setDerivedGaugeValid(updateDerivedGauge(value, o));
return (Comparable<?>) o.getDerivedGauge();
}
@Override
synchronized void onErrorNotification(MonitorNotification notification) {
final CounterMonitorObservedObject o = (CounterMonitorObservedObject)
getObservedObject(notification.getObservedObject());
if (o == null)
return;
// Reset values.
//
o.setModulusExceeded(false);
o.setEventAlreadyNotified(false);
o.setPreviousScanCounter(null);
}
@Override
synchronized MonitorNotification buildAlarmNotification(
ObjectName object,
String attribute,
Comparable<?> value) {
final CounterMonitorObservedObject o =
(CounterMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// Notify the listeners and update the threshold if
// the updated derived gauge value is valid.
//
final MonitorNotification alarm;
if (o.getDerivedGaugeValid()) {
alarm = updateNotifications(o);
updateThreshold(o);
} else {
alarm = null;
}
return alarm;
}
/** {@collect.stats}
* Tests if the threshold, offset and modulus of the specified observed
* object are of the same type as the counter. Only integer types are
* allowed.
*
* Note:
* If the optional offset or modulus have not been initialized, their
* default value is an Integer object with a value equal to zero.
*
* @param object The observed object.
* @param attribute The observed attribute.
* @param value The sample value.
* @return <CODE>true</CODE> if type is the same,
* <CODE>false</CODE> otherwise.
*/
@Override
synchronized boolean isThresholdTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
final CounterMonitorObservedObject o =
(CounterMonitorObservedObject) getObservedObject(object);
if (o == null)
return false;
Class<? extends Number> c = classForType(o.getType());
return (c.isInstance(o.getThreshold()) &&
isValidForType(offset, c) &&
isValidForType(modulus, c));
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
// jmx imports
//
import javax.management.ObjectName;
/** {@collect.stats}
* Exposes the remote management interface of monitor MBeans.
*
*
* @since 1.5
*/
public interface MonitorMBean {
/** {@collect.stats}
* Starts the monitor.
*/
public void start();
/** {@collect.stats}
* Stops the monitor.
*/
public void stop();
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Adds the specified object in the set of observed MBeans.
*
* @param object The object to observe.
* @exception java.lang.IllegalArgumentException the specified object is null.
*
*/
public void addObservedObject(ObjectName object) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Removes the specified object from the set of observed MBeans.
*
* @param object The object to remove.
*
*/
public void removeObservedObject(ObjectName object);
/** {@collect.stats}
* Tests whether the specified object is in the set of observed MBeans.
*
* @param object The object to check.
* @return <CODE>true</CODE> if the specified object is in the set, <CODE>false</CODE> otherwise.
*
*/
public boolean containsObservedObject(ObjectName object);
/** {@collect.stats}
* Returns an array containing the objects being observed.
*
* @return The objects being observed.
*
*/
public ObjectName[] getObservedObjects();
/** {@collect.stats}
* Gets the object name of the object being observed.
*
* @return The object being observed.
*
* @see #setObservedObject
*
* @deprecated As of JMX 1.2, replaced by {@link #getObservedObjects}
*/
@Deprecated
public ObjectName getObservedObject();
/** {@collect.stats}
* Sets the object to observe identified by its object name.
*
* @param object The object to observe.
*
* @see #getObservedObject
*
* @deprecated As of JMX 1.2, replaced by {@link #addObservedObject}
*/
@Deprecated
public void setObservedObject(ObjectName object);
/** {@collect.stats}
* Gets the attribute being observed.
*
* @return The attribute being observed.
*
* @see #setObservedAttribute
*/
public String getObservedAttribute();
/** {@collect.stats}
* Sets the attribute to observe.
*
* @param attribute The attribute to observe.
*
* @see #getObservedAttribute
*/
public void setObservedAttribute(String attribute);
/** {@collect.stats}
* Gets the granularity period (in milliseconds).
*
* @return The granularity period.
*
* @see #setGranularityPeriod
*/
public long getGranularityPeriod();
/** {@collect.stats}
* Sets the granularity period (in milliseconds).
*
* @param period The granularity period.
* @exception java.lang.IllegalArgumentException The granularity
* period is less than or equal to zero.
*
* @see #getGranularityPeriod
*/
public void setGranularityPeriod(long period) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Tests if the monitor MBean is active.
* A monitor MBean is marked active when the {@link #start start} method is called.
* It becomes inactive when the {@link #stop stop} method is called.
*
* @return <CODE>true</CODE> if the monitor MBean is active, <CODE>false</CODE> otherwise.
*/
public boolean isActive();
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
// jmx imports
//
import javax.management.ObjectName;
/** {@collect.stats}
* Exposes the remote management interface of the string monitor MBean.
*
*
* @since 1.5
*/
public interface StringMonitorMBean extends MonitorMBean {
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge.
*
* @return The derived gauge.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public String getDerivedGauge();
/** {@collect.stats}
* Gets the derived gauge timestamp.
*
* @return The derived gauge timestamp.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public long getDerivedGaugeTimeStamp();
/** {@collect.stats}
* Gets the derived gauge for the specified MBean.
*
* @param object the MBean for which the derived gauge is to be returned
* @return The derived gauge for the specified MBean if this MBean is in the
* set of observed MBeans, or <code>null</code> otherwise.
*
*/
public String getDerivedGauge(ObjectName object);
/** {@collect.stats}
* Gets the derived gauge timestamp for the specified MBean.
*
* @param object the MBean for which the derived gauge timestamp is to be returned
* @return The derived gauge timestamp for the specified MBean if this MBean
* is in the set of observed MBeans, or <code>null</code> otherwise.
*
*/
public long getDerivedGaugeTimeStamp(ObjectName object);
/** {@collect.stats}
* Gets the string to compare with the observed attribute.
*
* @return The string value.
*
* @see #setStringToCompare
*/
public String getStringToCompare();
/** {@collect.stats}
* Sets the string to compare with the observed attribute.
*
* @param value The string value.
* @exception java.lang.IllegalArgumentException The specified
* string to compare is null.
*
* @see #getStringToCompare
*/
public void setStringToCompare(String value) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the matching notification's on/off switch value.
*
* @return <CODE>true</CODE> if the string monitor notifies when
* matching, <CODE>false</CODE> otherwise.
*
* @see #setNotifyMatch
*/
public boolean getNotifyMatch();
/** {@collect.stats}
* Sets the matching notification's on/off switch value.
*
* @param value The matching notification's on/off switch value.
*
* @see #getNotifyMatch
*/
public void setNotifyMatch(boolean value);
/** {@collect.stats}
* Gets the differing notification's on/off switch value.
*
* @return <CODE>true</CODE> if the string monitor notifies when
* differing, <CODE>false</CODE> otherwise.
*
* @see #setNotifyDiffer
*/
public boolean getNotifyDiffer();
/** {@collect.stats}
* Sets the differing notification's on/off switch value.
*
* @param value The differing notification's on/off switch value.
*
* @see #getNotifyDiffer
*/
public void setNotifyDiffer(boolean value);
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
/** {@collect.stats}
* Exception thrown by the monitor when a monitor setting becomes invalid while the monitor is running.
* <P>
* As the monitor attributes may change at runtime, a check is performed before each observation.
* If a monitor attribute has become invalid, a monitor setting exception is thrown.
*
*
* @since 1.5
*/
public class MonitorSettingException extends javax.management.JMRuntimeException {
/* Serial version */
private static final long serialVersionUID = -8807913418190202007L;
/** {@collect.stats}
* Default constructor.
*/
public MonitorSettingException() {
super();
}
/** {@collect.stats}
* Constructor that allows an error message to be specified.
*
* @param message The specific error message.
*/
public MonitorSettingException(String message) {
super(message);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
import static com.sun.jmx.defaults.JmxProperties.MONITOR_LOGGER;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import com.sun.jmx.remote.util.EnvHelp;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import static javax.management.monitor.MonitorNotification.*;
import javax.management.openmbean.CompositeData;
/** {@collect.stats}
* Defines the part common to all monitor MBeans.
* A monitor MBean monitors values of an attribute common to a set of observed
* MBeans. The observed attribute is monitored at intervals specified by the
* granularity period. A gauge value (derived gauge) is derived from the values
* of the observed attribute.
*
*
* @since 1.5
*/
public abstract class Monitor
extends NotificationBroadcasterSupport
implements MonitorMBean, MBeanRegistration {
/*
* ------------------------------------------
* PACKAGE CLASSES
* ------------------------------------------
*/
static class ObservedObject {
public ObservedObject(ObjectName observedObject) {
this.observedObject = observedObject;
}
public final ObjectName getObservedObject() {
return observedObject;
}
public final synchronized int getAlreadyNotified() {
return alreadyNotified;
}
public final synchronized void setAlreadyNotified(int alreadyNotified) {
this.alreadyNotified = alreadyNotified;
}
public final synchronized Object getDerivedGauge() {
return derivedGauge;
}
public final synchronized void setDerivedGauge(Object derivedGauge) {
this.derivedGauge = derivedGauge;
}
public final synchronized long getDerivedGaugeTimeStamp() {
return derivedGaugeTimeStamp;
}
public final synchronized void setDerivedGaugeTimeStamp(
long derivedGaugeTimeStamp) {
this.derivedGaugeTimeStamp = derivedGaugeTimeStamp;
}
private final ObjectName observedObject;
private int alreadyNotified;
private Object derivedGauge;
private long derivedGaugeTimeStamp;
}
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Attribute to observe.
*/
private String observedAttribute;
/** {@collect.stats}
* Monitor granularity period (in milliseconds).
* The default value is set to 10 seconds.
*/
private long granularityPeriod = 10000;
/** {@collect.stats}
* Monitor state.
* The default value is set to <CODE>false</CODE>.
*/
private boolean isActive = false;
/** {@collect.stats}
* Monitor sequence number.
* The default value is set to 0.
*/
private final AtomicLong sequenceNumber = new AtomicLong();
/** {@collect.stats}
* Complex type attribute flag.
* The default value is set to <CODE>false</CODE>.
*/
private boolean isComplexTypeAttribute = false;
/** {@collect.stats}
* First attribute name extracted from complex type attribute name.
*/
private String firstAttribute;
/** {@collect.stats}
* Remaining attribute names extracted from complex type attribute name.
*/
private final List<String> remainingAttributes =
new CopyOnWriteArrayList<String>();
/** {@collect.stats}
* AccessControlContext of the Monitor.start() caller.
*/
private static final AccessControlContext noPermissionsACC =
new AccessControlContext(
new ProtectionDomain[] {new ProtectionDomain(null, null)});
private volatile AccessControlContext acc = noPermissionsACC;
/** {@collect.stats}
* Scheduler Service.
*/
private static final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor(
new DaemonThreadFactory("Scheduler"));
/** {@collect.stats}
* Map containing the thread pool executor per thread group.
*/
private static final Map<ThreadPoolExecutor, Void> executors =
new WeakHashMap<ThreadPoolExecutor, Void>();
/** {@collect.stats}
* Lock for executors map.
*/
private static final Object executorsLock = new Object();
/** {@collect.stats}
* Maximum Pool Size
*/
private static final int maximumPoolSize;
static {
final String maximumPoolSizeSysProp = "jmx.x.monitor.maximum.pool.size";
final String maximumPoolSizeStr = AccessController.doPrivileged(
new GetPropertyAction(maximumPoolSizeSysProp));
if (maximumPoolSizeStr == null ||
maximumPoolSizeStr.trim().length() == 0) {
maximumPoolSize = 10;
} else {
int maximumPoolSizeTmp = 10;
try {
maximumPoolSizeTmp = Integer.parseInt(maximumPoolSizeStr);
} catch (NumberFormatException e) {
if (MONITOR_LOGGER.isLoggable(Level.FINER)) {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"<static initializer>",
"Wrong value for " + maximumPoolSizeSysProp +
" system property", e);
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"<static initializer>",
maximumPoolSizeSysProp + " defaults to 10");
}
maximumPoolSizeTmp = 10;
}
if (maximumPoolSizeTmp < 1) {
maximumPoolSize = 1;
} else {
maximumPoolSize = maximumPoolSizeTmp;
}
}
}
/** {@collect.stats}
* Future associated to the current monitor task.
*/
private Future<?> monitorFuture;
/** {@collect.stats}
* Scheduler task to be executed by the Scheduler Service.
*/
private final SchedulerTask schedulerTask = new SchedulerTask();
/** {@collect.stats}
* ScheduledFuture associated to the current scheduler task.
*/
private ScheduledFuture<?> schedulerFuture;
/*
* ------------------------------------------
* PROTECTED VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* The amount by which the capacity of the monitor arrays are
* automatically incremented when their size becomes greater than
* their capacity.
*/
protected final static int capacityIncrement = 16;
/** {@collect.stats}
* The number of valid components in the vector of observed objects.
*
*/
protected int elementCount = 0;
/** {@collect.stats}
* Monitor errors that have already been notified.
* @deprecated equivalent to {@link #alreadyNotifieds}[0].
*/
@Deprecated
protected int alreadyNotified = 0;
/** {@collect.stats}
* <p>Selected monitor errors that have already been notified.</p>
*
* <p>Each element in this array corresponds to an observed object
* in the vector. It contains a bit mask of the flags {@link
* #OBSERVED_OBJECT_ERROR_NOTIFIED} etc, indicating whether the
* corresponding notification has already been sent for the MBean
* being monitored.</p>
*
*/
protected int alreadyNotifieds[] = new int[capacityIncrement];
/** {@collect.stats}
* Reference to the MBean server. This reference is null when the
* monitor MBean is not registered in an MBean server. This
* reference is initialized before the monitor MBean is registered
* in the MBean server.
* @see #preRegister(MBeanServer server, ObjectName name)
*/
protected MBeanServer server;
// Flags defining possible monitor errors.
//
/** {@collect.stats}
* This flag is used to reset the {@link #alreadyNotifieds
* alreadyNotifieds} monitor attribute.
*/
protected static final int RESET_FLAGS_ALREADY_NOTIFIED = 0;
/** {@collect.stats}
* Flag denoting that a notification has occurred after changing
* the observed object. This flag is used to check that the new
* observed object is registered in the MBean server at the time
* of the first notification.
*/
protected static final int OBSERVED_OBJECT_ERROR_NOTIFIED = 1;
/** {@collect.stats}
* Flag denoting that a notification has occurred after changing
* the observed attribute. This flag is used to check that the
* new observed attribute belongs to the observed object at the
* time of the first notification.
*/
protected static final int OBSERVED_ATTRIBUTE_ERROR_NOTIFIED = 2;
/** {@collect.stats}
* Flag denoting that a notification has occurred after changing
* the observed object or the observed attribute. This flag is
* used to check that the observed attribute type is correct
* (depending on the monitor in use) at the time of the first
* notification.
*/
protected static final int OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED = 4;
/** {@collect.stats}
* Flag denoting that a notification has occurred after changing
* the observed object or the observed attribute. This flag is
* used to notify any exception (except the cases described above)
* when trying to get the value of the observed attribute at the
* time of the first notification.
*/
protected static final int RUNTIME_ERROR_NOTIFIED = 8;
/** {@collect.stats}
* This field is retained for compatibility but should not be referenced.
*
* @deprecated No replacement.
*/
@Deprecated
protected String dbgTag = Monitor.class.getName();
/*
* ------------------------------------------
* PACKAGE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* List of ObservedObjects to which the attribute to observe belongs.
*/
final List<ObservedObject> observedObjects =
new CopyOnWriteArrayList<ObservedObject>();
/** {@collect.stats}
* Flag denoting that a notification has occurred after changing
* the threshold. This flag is used to notify any exception
* related to invalid thresholds settings.
*/
static final int THRESHOLD_ERROR_NOTIFIED = 16;
/** {@collect.stats}
* Enumeration used to keep trace of the derived gauge type
* in counter and gauge monitors.
*/
enum NumericalType { BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE };
/** {@collect.stats}
* Constant used to initialize all the numeric values.
*/
static final Integer INTEGER_ZERO = 0;
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Allows the monitor MBean to perform any operations it needs
* before being registered in the MBean server.
* <P>
* Initializes the reference to the MBean server.
*
* @param server The MBean server in which the monitor MBean will
* be registered.
* @param name The object name of the monitor MBean.
*
* @return The name of the monitor MBean registered.
*
* @exception Exception
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"preRegister(MBeanServer, ObjectName)",
"initialize the reference on the MBean server");
this.server = server;
return name;
}
/** {@collect.stats}
* Allows the monitor MBean to perform any operations needed after
* having been registered in the MBean server or after the
* registration has failed.
* <P>
* Not used in this context.
*/
public void postRegister(Boolean registrationDone) {
}
/** {@collect.stats}
* Allows the monitor MBean to perform any operations it needs
* before being unregistered by the MBean server.
* <P>
* Stops the monitor.
*
* @exception Exception
*/
public void preDeregister() throws Exception {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"preDeregister()", "stop the monitor");
// Stop the Monitor.
//
stop();
}
/** {@collect.stats}
* Allows the monitor MBean to perform any operations needed after
* having been unregistered by the MBean server.
* <P>
* Not used in this context.
*/
public void postDeregister() {
}
/** {@collect.stats}
* Starts the monitor.
*/
public abstract void start();
/** {@collect.stats}
* Stops the monitor.
*/
public abstract void stop();
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Returns the object name of the first object in the set of observed
* MBeans, or <code>null</code> if there is no such object.
*
* @return The object being observed.
*
* @see #setObservedObject(ObjectName)
*
* @deprecated As of JMX 1.2, replaced by {@link #getObservedObjects}
*/
@Deprecated
public synchronized ObjectName getObservedObject() {
if (observedObjects.isEmpty()) {
return null;
} else {
return observedObjects.get(0).getObservedObject();
}
}
/** {@collect.stats}
* Removes all objects from the set of observed objects, and then adds the
* specified object.
*
* @param object The object to observe.
* @exception IllegalArgumentException The specified
* object is null.
*
* @see #getObservedObject()
*
* @deprecated As of JMX 1.2, replaced by {@link #addObservedObject}
*/
@Deprecated
public synchronized void setObservedObject(ObjectName object)
throws IllegalArgumentException {
if (object == null)
throw new IllegalArgumentException("Null observed object");
if (observedObjects.size() == 1 && containsObservedObject(object))
return;
observedObjects.clear();
addObservedObject(object);
}
/** {@collect.stats}
* Adds the specified object in the set of observed MBeans, if this object
* is not already present.
*
* @param object The object to observe.
* @exception IllegalArgumentException The specified object is null.
*
*/
public synchronized void addObservedObject(ObjectName object)
throws IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException("Null observed object");
}
// Check that the specified object is not already contained.
//
if (containsObservedObject(object))
return;
// Add the specified object in the list.
//
ObservedObject o = createObservedObject(object);
o.setAlreadyNotified(RESET_FLAGS_ALREADY_NOTIFIED);
o.setDerivedGauge(INTEGER_ZERO);
o.setDerivedGaugeTimeStamp(System.currentTimeMillis());
observedObjects.add(o);
// Update legacy protected stuff.
//
createAlreadyNotified();
}
/** {@collect.stats}
* Removes the specified object from the set of observed MBeans.
*
* @param object The object to remove.
*
*/
public synchronized void removeObservedObject(ObjectName object) {
// Check for null object.
//
if (object == null)
return;
final ObservedObject o = getObservedObject(object);
if (o != null) {
// Remove the specified object from the list.
//
observedObjects.remove(o);
// Update legacy protected stuff.
//
createAlreadyNotified();
}
}
/** {@collect.stats}
* Tests whether the specified object is in the set of observed MBeans.
*
* @param object The object to check.
* @return <CODE>true</CODE> if the specified object is present,
* <CODE>false</CODE> otherwise.
*
*/
public synchronized boolean containsObservedObject(ObjectName object) {
return getObservedObject(object) != null;
}
/** {@collect.stats}
* Returns an array containing the objects being observed.
*
* @return The objects being observed.
*
*/
public synchronized ObjectName[] getObservedObjects() {
ObjectName[] names = new ObjectName[observedObjects.size()];
for (int i = 0; i < names.length; i++)
names[i] = observedObjects.get(i).getObservedObject();
return names;
}
/** {@collect.stats}
* Gets the attribute being observed.
* <BR>The observed attribute is not initialized by default (set to null).
*
* @return The attribute being observed.
*
* @see #setObservedAttribute
*/
public synchronized String getObservedAttribute() {
return observedAttribute;
}
/** {@collect.stats}
* Sets the attribute to observe.
* <BR>The observed attribute is not initialized by default (set to null).
*
* @param attribute The attribute to observe.
* @exception IllegalArgumentException The specified
* attribute is null.
*
* @see #getObservedAttribute
*/
public void setObservedAttribute(String attribute)
throws IllegalArgumentException {
if (attribute == null) {
throw new IllegalArgumentException("Null observed attribute");
}
// Update alreadyNotified array.
//
synchronized (this) {
if (observedAttribute != null &&
observedAttribute.equals(attribute))
return;
observedAttribute = attribute;
// Reset the complex type attribute information
// such that it is recalculated again.
//
cleanupIsComplexTypeAttribute();
int index = 0;
for (ObservedObject o : observedObjects) {
resetAlreadyNotified(o, index++,
OBSERVED_ATTRIBUTE_ERROR_NOTIFIED |
OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED);
}
}
}
/** {@collect.stats}
* Gets the granularity period (in milliseconds).
* <BR>The default value of the granularity period is 10 seconds.
*
* @return The granularity period value.
*
* @see #setGranularityPeriod
*/
public synchronized long getGranularityPeriod() {
return granularityPeriod;
}
/** {@collect.stats}
* Sets the granularity period (in milliseconds).
* <BR>The default value of the granularity period is 10 seconds.
*
* @param period The granularity period value.
* @exception IllegalArgumentException The granularity
* period is less than or equal to zero.
*
* @see #getGranularityPeriod
*/
public synchronized void setGranularityPeriod(long period)
throws IllegalArgumentException {
if (period <= 0) {
throw new IllegalArgumentException("Nonpositive granularity " +
"period");
}
if (granularityPeriod == period)
return;
granularityPeriod = period;
// Reschedule the scheduler task if the monitor is active.
//
if (isActive()) {
cleanupFutures();
schedulerFuture = scheduler.schedule(schedulerTask,
period,
TimeUnit.MILLISECONDS);
}
}
/** {@collect.stats}
* Tests whether the monitor MBean is active. A monitor MBean is
* marked active when the {@link #start start} method is called.
* It becomes inactive when the {@link #stop stop} method is
* called.
*
* @return <CODE>true</CODE> if the monitor MBean is active,
* <CODE>false</CODE> otherwise.
*/
/* This method must be synchronized so that the monitoring thread will
correctly see modifications to the isActive variable. See the MonitorTask
action executed by the Scheduled Executor Service. */
public synchronized boolean isActive() {
return isActive;
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Starts the monitor.
*/
void doStart() {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"doStart()", "start the monitor");
synchronized (this) {
if (isActive()) {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"doStart()", "the monitor is already active");
return;
}
isActive = true;
// Reset the complex type attribute information
// such that it is recalculated again.
//
cleanupIsComplexTypeAttribute();
// Cache the AccessControlContext of the Monitor.start() caller.
// The monitor tasks will be executed within this context.
//
acc = AccessController.getContext();
// Start the scheduler.
//
cleanupFutures();
schedulerTask.setMonitorTask(new MonitorTask());
schedulerFuture = scheduler.schedule(schedulerTask,
getGranularityPeriod(),
TimeUnit.MILLISECONDS);
}
}
/** {@collect.stats}
* Stops the monitor.
*/
void doStop() {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"doStop()", "stop the monitor");
synchronized (this) {
if (!isActive()) {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"doStop()", "the monitor is not active");
return;
}
isActive = false;
// Cancel the scheduler task associated with the
// scheduler and its associated monitor task.
//
cleanupFutures();
// Reset the AccessControlContext.
//
acc = noPermissionsACC;
// Reset the complex type attribute information
// such that it is recalculated again.
//
cleanupIsComplexTypeAttribute();
}
}
/** {@collect.stats}
* Gets the derived gauge of the specified object, if this object is
* contained in the set of observed MBeans, or <code>null</code> otherwise.
*
* @param object the name of the object whose derived gauge is to
* be returned.
*
* @return The derived gauge of the specified object.
*
* @since 1.6
*/
synchronized Object getDerivedGauge(ObjectName object) {
final ObservedObject o = getObservedObject(object);
return o == null ? null : o.getDerivedGauge();
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the specified object, if
* this object is contained in the set of observed MBeans, or
* <code>0</code> otherwise.
*
* @param object the name of the object whose derived gauge
* timestamp is to be returned.
*
* @return The derived gauge timestamp of the specified object.
*
*/
synchronized long getDerivedGaugeTimeStamp(ObjectName object) {
final ObservedObject o = getObservedObject(object);
return o == null ? 0 : o.getDerivedGaugeTimeStamp();
}
Object getAttribute(MBeanServerConnection mbsc,
ObjectName object,
String attribute)
throws AttributeNotFoundException,
InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException {
// Check for "ObservedAttribute" replacement.
// This could happen if a thread A called setObservedAttribute()
// while other thread B was in the middle of the monitor() method
// and received the old observed attribute value.
//
final boolean lookupMBeanInfo;
synchronized (this) {
if (!isActive())
throw new IllegalArgumentException(
"The monitor has been stopped");
if (!attribute.equals(getObservedAttribute()))
throw new IllegalArgumentException(
"The observed attribute has been changed");
lookupMBeanInfo =
(firstAttribute == null && attribute.indexOf('.') != -1);
}
// Look up MBeanInfo if needed
//
final MBeanInfo mbi;
if (lookupMBeanInfo) {
try {
mbi = mbsc.getMBeanInfo(object);
} catch (IntrospectionException e) {
throw new IllegalArgumentException(e);
}
} else {
mbi = null;
}
// Check for complex type attribute
//
final String fa;
synchronized (this) {
if (!isActive())
throw new IllegalArgumentException(
"The monitor has been stopped");
if (!attribute.equals(getObservedAttribute()))
throw new IllegalArgumentException(
"The observed attribute has been changed");
if (firstAttribute == null) {
if (attribute.indexOf('.') != -1) {
MBeanAttributeInfo mbaiArray[] = mbi.getAttributes();
for (MBeanAttributeInfo mbai : mbaiArray) {
if (attribute.equals(mbai.getName())) {
firstAttribute = attribute;
break;
}
}
if (firstAttribute == null) {
String tokens[] = attribute.split("\\.", -1);
firstAttribute = tokens[0];
for (int i = 1; i < tokens.length; i++)
remainingAttributes.add(tokens[i]);
isComplexTypeAttribute = true;
}
} else {
firstAttribute = attribute;
}
}
fa = firstAttribute;
}
return mbsc.getAttribute(object, fa);
}
Comparable<?> getComparableFromAttribute(ObjectName object,
String attribute,
Object value)
throws AttributeNotFoundException {
if (isComplexTypeAttribute) {
Object v = value;
for (String attr : remainingAttributes)
v = introspect(object, attr, v);
return (Comparable<?>) v;
} else {
return (Comparable<?>) value;
}
}
Object introspect(ObjectName object,
String attribute,
Object value)
throws AttributeNotFoundException {
try {
if (value.getClass().isArray() && attribute.equals("length")) {
return Array.getLength(value);
} else if (value instanceof CompositeData) {
return ((CompositeData) value).get(attribute);
} else {
// Java Beans introspection
//
BeanInfo bi = Introspector.getBeanInfo(value.getClass());
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (PropertyDescriptor pd : pds)
if (pd.getName().equals(attribute))
return pd.getReadMethod().invoke(value);
throw new AttributeNotFoundException(
"Could not find the getter method for the property " +
attribute + " using the Java Beans introspector");
}
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (AttributeNotFoundException e) {
throw e;
} catch (Exception e) {
throw EnvHelp.initCause(
new AttributeNotFoundException(e.getMessage()), e);
}
}
boolean isComparableTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
return true;
}
String buildErrorNotification(ObjectName object,
String attribute,
Comparable<?> value) {
return null;
}
void onErrorNotification(MonitorNotification notification) {
}
Comparable<?> getDerivedGaugeFromComparable(ObjectName object,
String attribute,
Comparable<?> value) {
return (Comparable<?>) value;
}
MonitorNotification buildAlarmNotification(ObjectName object,
String attribute,
Comparable<?> value){
return null;
}
boolean isThresholdTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
return true;
}
static Class<? extends Number> classForType(NumericalType type) {
switch (type) {
case BYTE:
return Byte.class;
case SHORT:
return Short.class;
case INTEGER:
return Integer.class;
case LONG:
return Long.class;
case FLOAT:
return Float.class;
case DOUBLE:
return Double.class;
default:
throw new IllegalArgumentException(
"Unsupported numerical type");
}
}
static boolean isValidForType(Object value, Class<? extends Number> c) {
return ((value == INTEGER_ZERO) || c.isInstance(value));
}
/** {@collect.stats}
* Get the specified {@code ObservedObject} if this object is
* contained in the set of observed MBeans, or {@code null}
* otherwise.
*
* @param object the name of the {@code ObservedObject} to retrieve.
*
* @return The {@code ObservedObject} associated to the supplied
* {@code ObjectName}.
*
* @since 1.6
*/
synchronized ObservedObject getObservedObject(ObjectName object) {
for (ObservedObject o : observedObjects)
if (o.getObservedObject().equals(object))
return o;
return null;
}
/** {@collect.stats}
* Factory method for ObservedObject creation.
*
* @since 1.6
*/
ObservedObject createObservedObject(ObjectName object) {
return new ObservedObject(object);
}
/** {@collect.stats}
* Create the {@link #alreadyNotified} array from
* the {@code ObservedObject} array list.
*/
synchronized void createAlreadyNotified() {
// Update elementCount.
//
elementCount = observedObjects.size();
// Update arrays.
//
alreadyNotifieds = new int[elementCount];
for (int i = 0; i < elementCount; i++) {
alreadyNotifieds[i] = observedObjects.get(i).getAlreadyNotified();
}
updateDeprecatedAlreadyNotified();
}
/** {@collect.stats}
* Update the deprecated {@link #alreadyNotified} field.
*/
synchronized void updateDeprecatedAlreadyNotified() {
if (elementCount > 0)
alreadyNotified = alreadyNotifieds[0];
else
alreadyNotified = 0;
}
/** {@collect.stats}
* Update the {@link #alreadyNotifieds} array element at the given index
* with the already notified flag in the given {@code ObservedObject}.
* Ensure the deprecated {@link #alreadyNotified} field is updated
* if appropriate.
*/
synchronized void updateAlreadyNotified(ObservedObject o, int index) {
alreadyNotifieds[index] = o.getAlreadyNotified();
if (index == 0)
updateDeprecatedAlreadyNotified();
}
/** {@collect.stats}
* Check if the given bits in the given element of {@link #alreadyNotifieds}
* are set.
*/
synchronized boolean isAlreadyNotified(ObservedObject o, int mask) {
return ((o.getAlreadyNotified() & mask) != 0);
}
/** {@collect.stats}
* Set the given bits in the given element of {@link #alreadyNotifieds}.
* Ensure the deprecated {@link #alreadyNotified} field is updated
* if appropriate.
*/
synchronized void setAlreadyNotified(ObservedObject o, int index,
int mask, int an[]) {
final int i = computeAlreadyNotifiedIndex(o, index, an);
if (i == -1)
return;
o.setAlreadyNotified(o.getAlreadyNotified() | mask);
updateAlreadyNotified(o, i);
}
/** {@collect.stats}
* Reset the given bits in the given element of {@link #alreadyNotifieds}.
* Ensure the deprecated {@link #alreadyNotified} field is updated
* if appropriate.
*/
synchronized void resetAlreadyNotified(ObservedObject o,
int index, int mask) {
o.setAlreadyNotified(o.getAlreadyNotified() & ~mask);
updateAlreadyNotified(o, index);
}
/** {@collect.stats}
* Reset all bits in the given element of {@link #alreadyNotifieds}.
* Ensure the deprecated {@link #alreadyNotified} field is updated
* if appropriate.
*/
synchronized void resetAllAlreadyNotified(ObservedObject o,
int index, int an[]) {
final int i = computeAlreadyNotifiedIndex(o, index, an);
if (i == -1)
return;
o.setAlreadyNotified(RESET_FLAGS_ALREADY_NOTIFIED);
updateAlreadyNotified(o, index);
}
/** {@collect.stats}
* Check if the {@link #alreadyNotifieds} array has been modified.
* If true recompute the index for the given observed object.
*/
synchronized int computeAlreadyNotifiedIndex(ObservedObject o,
int index, int an[]) {
if (an == alreadyNotifieds) {
return index;
} else {
return observedObjects.indexOf(o);
}
}
/*
* ------------------------------------------
* PRIVATE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* This method is used by the monitor MBean to create and send a
* monitor notification to all the listeners registered for this
* kind of notification.
*
* @param type The notification type.
* @param timeStamp The notification emission date.
* @param msg The notification message.
* @param derGauge The derived gauge.
* @param trigger The threshold/string (depending on the monitor
* type) that triggered off the notification.
* @param object The ObjectName of the observed object that triggered
* off the notification.
* @param onError Flag indicating if this monitor notification is
* an error notification or an alarm notification.
*/
private void sendNotification(String type, long timeStamp, String msg,
Object derGauge, Object trigger,
ObjectName object, boolean onError) {
if (!isActive())
return;
if (MONITOR_LOGGER.isLoggable(Level.FINER)) {
MONITOR_LOGGER.logp(Level.FINER, Monitor.class.getName(),
"sendNotification", "send notification: " +
"\n\tNotification observed object = " + object +
"\n\tNotification observed attribute = " + observedAttribute +
"\n\tNotification derived gauge = " + derGauge);
}
long seqno = sequenceNumber.getAndIncrement();
MonitorNotification mn =
new MonitorNotification(type,
this,
seqno,
timeStamp,
msg,
object,
observedAttribute,
derGauge,
trigger);
if (onError)
onErrorNotification(mn);
sendNotification(mn);
}
/** {@collect.stats}
* This method is called by the monitor each time
* the granularity period has been exceeded.
* @param o The observed object.
*/
private void monitor(ObservedObject o, int index, int an[]) {
String attribute = null;
String notifType = null;
String msg = null;
Object derGauge = null;
Object trigger = null;
ObjectName object = null;
Comparable<?> value = null;
MonitorNotification alarm = null;
if (!isActive())
return;
// Check that neither the observed object nor the
// observed attribute are null. If the observed
// object or observed attribute is null, this means
// that the monitor started before a complete
// initialization and nothing is done.
//
synchronized (this) {
object = o.getObservedObject();
attribute = getObservedAttribute();
if (object == null || attribute == null) {
return;
}
}
// Check that the observed object is registered in the
// MBean server and that the observed attribute
// belongs to the observed object.
//
Object attributeValue = null;
try {
attributeValue = getAttribute(server, object, attribute);
if (attributeValue == null)
if (isAlreadyNotified(
o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
setAlreadyNotified(
o, index, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
msg = "The observed attribute value is null.";
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
}
} catch (NullPointerException np_ex) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
msg =
"The monitor must be registered in the MBean " +
"server or an MBeanServerConnection must be " +
"explicitly supplied.";
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", np_ex.toString());
}
} catch (InstanceNotFoundException inf_ex) {
if (isAlreadyNotified(o, OBSERVED_OBJECT_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_OBJECT_ERROR;
setAlreadyNotified(
o, index, OBSERVED_OBJECT_ERROR_NOTIFIED, an);
msg =
"The observed object must be accessible in " +
"the MBeanServerConnection.";
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", inf_ex.toString());
}
} catch (AttributeNotFoundException anf_ex) {
if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_ATTRIBUTE_ERROR;
setAlreadyNotified(
o, index, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED, an);
msg =
"The observed attribute must be accessible in " +
"the observed object.";
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", anf_ex.toString());
}
} catch (MBeanException mb_ex) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
msg = mb_ex.getMessage() == null ? "" : mb_ex.getMessage();
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", mb_ex.toString());
}
} catch (ReflectionException ref_ex) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED)) {
return;
} else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
msg = ref_ex.getMessage() == null ? "" : ref_ex.getMessage();
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", ref_ex.toString());
}
} catch (IOException io_ex) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
msg = io_ex.getMessage() == null ? "" : io_ex.getMessage();
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", io_ex.toString());
}
} catch (RuntimeException rt_ex) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index, RUNTIME_ERROR_NOTIFIED, an);
msg = rt_ex.getMessage() == null ? "" : rt_ex.getMessage();
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST, Monitor.class.getName(),
"monitor", rt_ex.toString());
}
}
synchronized (this) {
// Check if the monitor has been stopped.
//
if (!isActive())
return;
// Check if the observed attribute has been changed.
//
// Avoid race condition where mbs.getAttribute() succeeded but
// another thread replaced the observed attribute meanwhile.
//
// Avoid setting computed derived gauge on erroneous attribute.
//
if (!attribute.equals(getObservedAttribute()))
return;
// Derive a Comparable object from the ObservedAttribute value
// if the type of the ObservedAttribute value is a complex type.
//
if (msg == null) {
try {
value = getComparableFromAttribute(object,
attribute,
attributeValue);
} catch (ClassCastException e) {
if (isAlreadyNotified(
o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
setAlreadyNotified(o, index,
OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
msg =
"The observed attribute value does not " +
"implement the Comparable interface.";
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", e.toString());
}
} catch (AttributeNotFoundException e) {
if (isAlreadyNotified(o, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_ATTRIBUTE_ERROR;
setAlreadyNotified(
o, index, OBSERVED_ATTRIBUTE_ERROR_NOTIFIED, an);
msg =
"The observed attribute must be accessible in " +
"the observed object.";
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", e.toString());
}
} catch (RuntimeException e) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index,
RUNTIME_ERROR_NOTIFIED, an);
msg = e.getMessage() == null ? "" : e.getMessage();
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", e.toString());
}
}
}
// Check that the observed attribute type is supported by this
// monitor.
//
if (msg == null) {
if (!isComparableTypeValid(object, attribute, value)) {
if (isAlreadyNotified(
o, OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED))
return;
else {
notifType = OBSERVED_ATTRIBUTE_TYPE_ERROR;
setAlreadyNotified(o, index,
OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED, an);
msg = "The observed attribute type is not valid.";
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
}
}
}
// Check that threshold type is supported by this monitor.
//
if (msg == null) {
if (!isThresholdTypeValid(object, attribute, value)) {
if (isAlreadyNotified(o, THRESHOLD_ERROR_NOTIFIED))
return;
else {
notifType = THRESHOLD_ERROR;
setAlreadyNotified(o, index,
THRESHOLD_ERROR_NOTIFIED, an);
msg = "The threshold type is not valid.";
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
}
}
}
// Let someone subclassing the monitor to perform additional
// monitor consistency checks and report errors if necessary.
//
if (msg == null) {
msg = buildErrorNotification(object, attribute, value);
if (msg != null) {
if (isAlreadyNotified(o, RUNTIME_ERROR_NOTIFIED))
return;
else {
notifType = RUNTIME_ERROR;
setAlreadyNotified(o, index,
RUNTIME_ERROR_NOTIFIED, an);
MONITOR_LOGGER.logp(Level.FINEST,
Monitor.class.getName(), "monitor", msg);
}
}
}
// If no errors were found then clear all error flags and
// let the monitor decide if a notification must be sent.
//
if (msg == null) {
// Clear all already notified flags.
//
resetAllAlreadyNotified(o, index, an);
// Get derived gauge from comparable value.
//
derGauge = getDerivedGaugeFromComparable(object,
attribute,
value);
o.setDerivedGauge(derGauge);
o.setDerivedGaugeTimeStamp(System.currentTimeMillis());
// Check if an alarm must be fired.
//
alarm = buildAlarmNotification(object,
attribute,
(Comparable<?>) derGauge);
}
}
// Notify monitor errors
//
if (msg != null)
sendNotification(notifType,
System.currentTimeMillis(),
msg,
derGauge,
trigger,
object,
true);
// Notify monitor alarms
//
if (alarm != null && alarm.getType() != null)
sendNotification(alarm.getType(),
System.currentTimeMillis(),
alarm.getMessage(),
derGauge,
alarm.getTrigger(),
object,
false);
}
/** {@collect.stats}
* Cleanup the scheduler and monitor tasks futures.
*/
private synchronized void cleanupFutures() {
if (schedulerFuture != null) {
schedulerFuture.cancel(false);
schedulerFuture = null;
}
if (monitorFuture != null) {
monitorFuture.cancel(false);
monitorFuture = null;
}
}
/** {@collect.stats}
* Cleanup the "is complex type attribute" info.
*/
private synchronized void cleanupIsComplexTypeAttribute() {
firstAttribute = null;
remainingAttributes.clear();
isComplexTypeAttribute = false;
}
/** {@collect.stats}
* SchedulerTask nested class: This class implements the Runnable interface.
*
* The SchedulerTask is executed periodically with a given fixed delay by
* the Scheduled Executor Service.
*/
private class SchedulerTask implements Runnable {
private MonitorTask task;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
public SchedulerTask() {
}
/*
* ------------------------------------------
* GETTERS/SETTERS
* ------------------------------------------
*/
public void setMonitorTask(MonitorTask task) {
this.task = task;
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
public void run() {
synchronized (Monitor.this) {
Monitor.this.monitorFuture = task.submit();
}
}
}
/** {@collect.stats}
* MonitorTask nested class: This class implements the Runnable interface.
*
* The MonitorTask is executed periodically with a given fixed delay by the
* Scheduled Executor Service.
*/
private class MonitorTask implements Runnable {
private ThreadPoolExecutor executor;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
public MonitorTask() {
// Find out if there's already an existing executor for the calling
// thread and reuse it. Otherwise, create a new one and store it in
// the executors map. If there is a SecurityManager, the group of
// System.getSecurityManager() is used, else the group of the thread
// instantiating this MonitorTask, i.e. the group of the thread that
// calls "Monitor.start()".
SecurityManager s = System.getSecurityManager();
ThreadGroup group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
synchronized (executorsLock) {
for (ThreadPoolExecutor e : executors.keySet()) {
DaemonThreadFactory tf =
(DaemonThreadFactory) e.getThreadFactory();
ThreadGroup tg = tf.getThreadGroup();
if (tg == group) {
executor = e;
break;
}
}
if (executor == null) {
executor = new ThreadPoolExecutor(
maximumPoolSize,
maximumPoolSize,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
new DaemonThreadFactory("ThreadGroup<" +
group.getName() + "> Executor", group));
executor.allowCoreThreadTimeOut(true);
executors.put(executor, null);
}
}
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
public Future<?> submit() {
return executor.submit(this);
}
public void run() {
final ScheduledFuture<?> sf;
final AccessControlContext ac;
synchronized (Monitor.this) {
sf = Monitor.this.schedulerFuture;
ac = Monitor.this.acc;
}
PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
public Void run() {
if (Monitor.this.isActive()) {
final int an[] = alreadyNotifieds;
int index = 0;
for (ObservedObject o : Monitor.this.observedObjects) {
if (Monitor.this.isActive()) {
Monitor.this.monitor(o, index++, an);
}
}
}
return null;
}
};
if (ac == null) {
throw new SecurityException("AccessControlContext cannot be null");
}
AccessController.doPrivileged(action, ac);
synchronized (Monitor.this) {
if (Monitor.this.isActive() &&
Monitor.this.schedulerFuture == sf) {
Monitor.this.monitorFuture = null;
Monitor.this.schedulerFuture =
scheduler.schedule(Monitor.this.schedulerTask,
Monitor.this.getGranularityPeriod(),
TimeUnit.MILLISECONDS);
}
}
}
}
/** {@collect.stats}
* Daemon thread factory used by the monitor executors.
* <P>
* This factory creates all new threads used by an Executor in
* the same ThreadGroup. If there is a SecurityManager, it uses
* the group of System.getSecurityManager(), else the group of
* the thread instantiating this DaemonThreadFactory. Each new
* thread is created as a daemon thread with priority
* Thread.NORM_PRIORITY. New threads have names accessible via
* Thread.getName() of "JMX Monitor <pool-name> Pool [Thread-M]",
* where M is the sequence number of the thread created by this
* factory.
*/
private static class DaemonThreadFactory implements ThreadFactory {
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
final String nameSuffix = "]";
public DaemonThreadFactory(String poolName) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "JMX Monitor " + poolName + " Pool [Thread-";
}
public DaemonThreadFactory(String poolName, ThreadGroup threadGroup) {
group = threadGroup;
namePrefix = "JMX Monitor " + poolName + " Pool [Thread-";
}
public ThreadGroup getThreadGroup() {
return group;
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group,
r,
namePrefix +
threadNumber.getAndIncrement() +
nameSuffix,
0);
t.setDaemon(true);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
import static com.sun.jmx.defaults.JmxProperties.MONITOR_LOGGER;
import java.util.logging.Level;
import javax.management.ObjectName;
import javax.management.MBeanNotificationInfo;
import static javax.management.monitor.MonitorNotification.*;
/** {@collect.stats}
* Defines a monitor MBean designed to observe the values of a string
* attribute.
* <P>
* A string monitor sends notifications as follows:
* <UL>
* <LI> if the attribute value matches the string to compare value,
* a {@link MonitorNotification#STRING_TO_COMPARE_VALUE_MATCHED
* match notification} is sent.
* The notify match flag must be set to <CODE>true</CODE>.
* <BR>Subsequent matchings of the string to compare values do not
* cause further notifications unless
* the attribute value differs from the string to compare value.
* <LI> if the attribute value differs from the string to compare value,
* a {@link MonitorNotification#STRING_TO_COMPARE_VALUE_DIFFERED
* differ notification} is sent.
* The notify differ flag must be set to <CODE>true</CODE>.
* <BR>Subsequent differences from the string to compare value do
* not cause further notifications unless
* the attribute value matches the string to compare value.
* </UL>
*
*
* @since 1.5
*/
public class StringMonitor extends Monitor implements StringMonitorMBean {
/*
* ------------------------------------------
* PACKAGE CLASSES
* ------------------------------------------
*/
static class StringMonitorObservedObject extends ObservedObject {
public StringMonitorObservedObject(ObjectName observedObject) {
super(observedObject);
}
public final synchronized int getStatus() {
return status;
}
public final synchronized void setStatus(int status) {
this.status = status;
}
private int status;
}
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* String to compare with the observed attribute.
* <BR>The default value is an empty character sequence.
*/
private String stringToCompare = "";
/** {@collect.stats}
* Flag indicating if the string monitor notifies when matching
* the string to compare.
* <BR>The default value is set to <CODE>false</CODE>.
*/
private boolean notifyMatch = false;
/** {@collect.stats}
* Flag indicating if the string monitor notifies when differing
* from the string to compare.
* <BR>The default value is set to <CODE>false</CODE>.
*/
private boolean notifyDiffer = false;
private static final String[] types = {
RUNTIME_ERROR,
OBSERVED_OBJECT_ERROR,
OBSERVED_ATTRIBUTE_ERROR,
OBSERVED_ATTRIBUTE_TYPE_ERROR,
STRING_TO_COMPARE_VALUE_MATCHED,
STRING_TO_COMPARE_VALUE_DIFFERED
};
private static final MBeanNotificationInfo[] notifsInfo = {
new MBeanNotificationInfo(
types,
"javax.management.monitor.MonitorNotification",
"Notifications sent by the StringMonitor MBean")
};
// Flags needed to implement the matching/differing mechanism.
//
private static final int MATCHING = 0;
private static final int DIFFERING = 1;
private static final int MATCHING_OR_DIFFERING = 2;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Default constructor.
*/
public StringMonitor() {
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Starts the string monitor.
*/
public synchronized void start() {
if (isActive()) {
MONITOR_LOGGER.logp(Level.FINER, StringMonitor.class.getName(),
"start", "the monitor is already active");
return;
}
// Reset values.
//
for (ObservedObject o : observedObjects) {
final StringMonitorObservedObject smo =
(StringMonitorObservedObject) o;
smo.setStatus(MATCHING_OR_DIFFERING);
}
doStart();
}
/** {@collect.stats}
* Stops the string monitor.
*/
public synchronized void stop() {
doStop();
}
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge of the specified object, if this object is
* contained in the set of observed MBeans, or <code>null</code> otherwise.
*
* @param object the name of the MBean whose derived gauge is required.
*
* @return The derived gauge of the specified object.
*
*/
@Override
public synchronized String getDerivedGauge(ObjectName object) {
return (String) super.getDerivedGauge(object);
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the specified object, if
* this object is contained in the set of observed MBeans, or
* <code>0</code> otherwise.
*
* @param object the name of the object whose derived gauge
* timestamp is to be returned.
*
* @return The derived gauge timestamp of the specified object.
*
*/
@Override
public synchronized long getDerivedGaugeTimeStamp(ObjectName object) {
return super.getDerivedGaugeTimeStamp(object);
}
/** {@collect.stats}
* Returns the derived gauge of the first object in the set of
* observed MBeans.
*
* @return The derived gauge.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public synchronized String getDerivedGauge() {
if (observedObjects.isEmpty()) {
return null;
} else {
return (String) observedObjects.get(0).getDerivedGauge();
}
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the first object in the set
* of observed MBeans.
*
* @return The derived gauge timestamp.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public synchronized long getDerivedGaugeTimeStamp() {
if (observedObjects.isEmpty()) {
return 0;
} else {
return observedObjects.get(0).getDerivedGaugeTimeStamp();
}
}
/** {@collect.stats}
* Gets the string to compare with the observed attribute common
* to all observed MBeans.
*
* @return The string value.
*
* @see #setStringToCompare
*/
public synchronized String getStringToCompare() {
return stringToCompare;
}
/** {@collect.stats}
* Sets the string to compare with the observed attribute common
* to all observed MBeans.
*
* @param value The string value.
*
* @exception IllegalArgumentException The specified
* string to compare is null.
*
* @see #getStringToCompare
*/
public synchronized void setStringToCompare(String value)
throws IllegalArgumentException {
if (value == null) {
throw new IllegalArgumentException("Null string to compare");
}
if (stringToCompare.equals(value))
return;
stringToCompare = value;
// Reset values.
//
for (ObservedObject o : observedObjects) {
final StringMonitorObservedObject smo =
(StringMonitorObservedObject) o;
smo.setStatus(MATCHING_OR_DIFFERING);
}
}
/** {@collect.stats}
* Gets the matching notification's on/off switch value common to
* all observed MBeans.
*
* @return <CODE>true</CODE> if the string monitor notifies when
* matching the string to compare, <CODE>false</CODE> otherwise.
*
* @see #setNotifyMatch
*/
public synchronized boolean getNotifyMatch() {
return notifyMatch;
}
/** {@collect.stats}
* Sets the matching notification's on/off switch value common to
* all observed MBeans.
*
* @param value The matching notification's on/off switch value.
*
* @see #getNotifyMatch
*/
public synchronized void setNotifyMatch(boolean value) {
if (notifyMatch == value)
return;
notifyMatch = value;
}
/** {@collect.stats}
* Gets the differing notification's on/off switch value common to
* all observed MBeans.
*
* @return <CODE>true</CODE> if the string monitor notifies when
* differing from the string to compare, <CODE>false</CODE> otherwise.
*
* @see #setNotifyDiffer
*/
public synchronized boolean getNotifyDiffer() {
return notifyDiffer;
}
/** {@collect.stats}
* Sets the differing notification's on/off switch value common to
* all observed MBeans.
*
* @param value The differing notification's on/off switch value.
*
* @see #getNotifyDiffer
*/
public synchronized void setNotifyDiffer(boolean value) {
if (notifyDiffer == value)
return;
notifyDiffer = value;
}
/** {@collect.stats}
* Returns a <CODE>NotificationInfo</CODE> object containing the name of
* the Java class of the notification and the notification types sent by
* the string monitor.
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return notifsInfo.clone();
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Factory method for ObservedObject creation.
*
* @since 1.6
*/
@Override
ObservedObject createObservedObject(ObjectName object) {
final StringMonitorObservedObject smo =
new StringMonitorObservedObject(object);
smo.setStatus(MATCHING_OR_DIFFERING);
return smo;
}
/** {@collect.stats}
* Check that the type of the supplied observed attribute
* value is one of the value types supported by this monitor.
*/
@Override
synchronized boolean isComparableTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
// Check that the observed attribute is of type "String".
//
if (value instanceof String) {
return true;
}
return false;
}
@Override
synchronized void onErrorNotification(MonitorNotification notification) {
final StringMonitorObservedObject o = (StringMonitorObservedObject)
getObservedObject(notification.getObservedObject());
if (o == null)
return;
// Reset values.
//
o.setStatus(MATCHING_OR_DIFFERING);
}
@Override
synchronized MonitorNotification buildAlarmNotification(
ObjectName object,
String attribute,
Comparable<?> value) {
String type = null;
String msg = null;
Object trigger = null;
final StringMonitorObservedObject o =
(StringMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// Send matching notification if notifyMatch is true.
// Send differing notification if notifyDiffer is true.
//
if (o.getStatus() == MATCHING_OR_DIFFERING) {
if (o.getDerivedGauge().equals(stringToCompare)) {
if (notifyMatch) {
type = STRING_TO_COMPARE_VALUE_MATCHED;
msg = "";
trigger = stringToCompare;
}
o.setStatus(DIFFERING);
} else {
if (notifyDiffer) {
type = STRING_TO_COMPARE_VALUE_DIFFERED;
msg = "";
trigger = stringToCompare;
}
o.setStatus(MATCHING);
}
} else {
if (o.getStatus() == MATCHING) {
if (o.getDerivedGauge().equals(stringToCompare)) {
if (notifyMatch) {
type = STRING_TO_COMPARE_VALUE_MATCHED;
msg = "";
trigger = stringToCompare;
}
o.setStatus(DIFFERING);
}
} else if (o.getStatus() == DIFFERING) {
if (!o.getDerivedGauge().equals(stringToCompare)) {
if (notifyDiffer) {
type = STRING_TO_COMPARE_VALUE_DIFFERED;
msg = "";
trigger = stringToCompare;
}
o.setStatus(MATCHING);
}
}
}
return new MonitorNotification(type,
this,
0,
0,
msg,
null,
null,
null,
trigger);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
// jmx imports
//
import javax.management.ObjectName;
/** {@collect.stats}
* Exposes the remote management interface of the gauge monitor MBean.
*
*
* @since 1.5
*/
public interface GaugeMonitorMBean extends MonitorMBean {
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge.
*
* @return The derived gauge.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public Number getDerivedGauge();
/** {@collect.stats}
* Gets the derived gauge timestamp.
*
* @return The derived gauge timestamp.
* @deprecated As of JMX 1.2, replaced by {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public long getDerivedGaugeTimeStamp();
/** {@collect.stats}
* Gets the derived gauge for the specified MBean.
*
* @param object the MBean for which the derived gauge is to be returned
* @return The derived gauge for the specified MBean if this MBean is in the
* set of observed MBeans, or <code>null</code> otherwise.
*
*/
public Number getDerivedGauge(ObjectName object);
/** {@collect.stats}
* Gets the derived gauge timestamp for the specified MBean.
*
* @param object the MBean for which the derived gauge timestamp is to be returned
* @return The derived gauge timestamp for the specified MBean if this MBean
* is in the set of observed MBeans, or <code>null</code> otherwise.
*
*/
public long getDerivedGaugeTimeStamp(ObjectName object);
/** {@collect.stats}
* Gets the high threshold value.
*
* @return The high threshold value.
*/
public Number getHighThreshold();
/** {@collect.stats}
* Gets the low threshold value.
*
* @return The low threshold value.
*/
public Number getLowThreshold();
/** {@collect.stats}
* Sets the high and the low threshold values.
*
* @param highValue The high threshold value.
* @param lowValue The low threshold value.
* @exception java.lang.IllegalArgumentException The specified high/low threshold is null
* or the low threshold is greater than the high threshold
* or the high threshold and the low threshold are not of the same type.
*/
public void setThresholds(Number highValue, Number lowValue) throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Gets the high notification's on/off switch value.
*
* @return <CODE>true</CODE> if the gauge monitor notifies when
* exceeding the high threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotifyHigh
*/
public boolean getNotifyHigh();
/** {@collect.stats}
* Sets the high notification's on/off switch value.
*
* @param value The high notification's on/off switch value.
*
* @see #getNotifyHigh
*/
public void setNotifyHigh(boolean value);
/** {@collect.stats}
* Gets the low notification's on/off switch value.
*
* @return <CODE>true</CODE> if the gauge monitor notifies when
* exceeding the low threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotifyLow
*/
public boolean getNotifyLow();
/** {@collect.stats}
* Sets the low notification's on/off switch value.
*
* @param value The low notification's on/off switch value.
*
* @see #getNotifyLow
*/
public void setNotifyLow(boolean value);
/** {@collect.stats}
* Gets the difference mode flag value.
*
* @return <CODE>true</CODE> if the difference mode is used,
* <CODE>false</CODE> otherwise.
*
* @see #setDifferenceMode
*/
public boolean getDifferenceMode();
/** {@collect.stats}
* Sets the difference mode flag value.
*
* @param value The difference mode flag value.
*
* @see #getDifferenceMode
*/
public void setDifferenceMode(boolean value);
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.monitor;
import static com.sun.jmx.defaults.JmxProperties.MONITOR_LOGGER;
import java.util.logging.Level;
import javax.management.MBeanNotificationInfo;
import javax.management.ObjectName;
import static javax.management.monitor.Monitor.NumericalType.*;
import static javax.management.monitor.MonitorNotification.*;
/** {@collect.stats}
* Defines a monitor MBean designed to observe the values of a gauge attribute.
*
* <P> A gauge monitor observes an attribute that is continuously
* variable with time. A gauge monitor sends notifications as
* follows:
*
* <UL>
*
* <LI> if the attribute value is increasing and becomes equal to or
* greater than the high threshold value, a {@link
* MonitorNotification#THRESHOLD_HIGH_VALUE_EXCEEDED threshold high
* notification} is sent. The notify high flag must be set to
* <CODE>true</CODE>.
*
* <BR>Subsequent crossings of the high threshold value do not cause
* further notifications unless the attribute value becomes equal to
* or less than the low threshold value.</LI>
*
* <LI> if the attribute value is decreasing and becomes equal to or
* less than the low threshold value, a {@link
* MonitorNotification#THRESHOLD_LOW_VALUE_EXCEEDED threshold low
* notification} is sent. The notify low flag must be set to
* <CODE>true</CODE>.
*
* <BR>Subsequent crossings of the low threshold value do not cause
* further notifications unless the attribute value becomes equal to
* or greater than the high threshold value.</LI>
*
* </UL>
*
* This provides a hysteresis mechanism to avoid repeated triggering
* of notifications when the attribute value makes small oscillations
* around the high or low threshold value.
*
* <P> If the gauge difference mode is used, the value of the derived
* gauge is calculated as the difference between the observed gauge
* values for two successive observations.
*
* <BR>The derived gauge value (V[t]) is calculated using the following method:
* <UL>
* <LI>V[t] = gauge[t] - gauge[t-GP]</LI>
* </UL>
*
* This implementation of the gauge monitor requires the observed
* attribute to be of the type integer or floating-point
* (<CODE>Byte</CODE>, <CODE>Integer</CODE>, <CODE>Short</CODE>,
* <CODE>Long</CODE>, <CODE>Float</CODE>, <CODE>Double</CODE>).
*
*
* @since 1.5
*/
public class GaugeMonitor extends Monitor implements GaugeMonitorMBean {
/*
* ------------------------------------------
* PACKAGE CLASSES
* ------------------------------------------
*/
static class GaugeMonitorObservedObject extends ObservedObject {
public GaugeMonitorObservedObject(ObjectName observedObject) {
super(observedObject);
}
public final synchronized boolean getDerivedGaugeValid() {
return derivedGaugeValid;
}
public final synchronized void setDerivedGaugeValid(
boolean derivedGaugeValid) {
this.derivedGaugeValid = derivedGaugeValid;
}
public final synchronized NumericalType getType() {
return type;
}
public final synchronized void setType(NumericalType type) {
this.type = type;
}
public final synchronized Number getPreviousScanGauge() {
return previousScanGauge;
}
public final synchronized void setPreviousScanGauge(
Number previousScanGauge) {
this.previousScanGauge = previousScanGauge;
}
public final synchronized int getStatus() {
return status;
}
public final synchronized void setStatus(int status) {
this.status = status;
}
private boolean derivedGaugeValid;
private NumericalType type;
private Number previousScanGauge;
private int status;
}
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Gauge high threshold.
*
* <BR>The default value is a null Integer object.
*/
private Number highThreshold = INTEGER_ZERO;
/** {@collect.stats}
* Gauge low threshold.
*
* <BR>The default value is a null Integer object.
*/
private Number lowThreshold = INTEGER_ZERO;
/** {@collect.stats}
* Flag indicating if the gauge monitor notifies when exceeding
* the high threshold.
*
* <BR>The default value is <CODE>false</CODE>.
*/
private boolean notifyHigh = false;
/** {@collect.stats}
* Flag indicating if the gauge monitor notifies when exceeding
* the low threshold.
*
* <BR>The default value is <CODE>false</CODE>.
*/
private boolean notifyLow = false;
/** {@collect.stats}
* Flag indicating if the gauge difference mode is used. If the
* gauge difference mode is used, the derived gauge is the
* difference between two consecutive observed values. Otherwise,
* the derived gauge is directly the value of the observed
* attribute.
*
* <BR>The default value is set to <CODE>false</CODE>.
*/
private boolean differenceMode = false;
private static final String[] types = {
RUNTIME_ERROR,
OBSERVED_OBJECT_ERROR,
OBSERVED_ATTRIBUTE_ERROR,
OBSERVED_ATTRIBUTE_TYPE_ERROR,
THRESHOLD_ERROR,
THRESHOLD_HIGH_VALUE_EXCEEDED,
THRESHOLD_LOW_VALUE_EXCEEDED
};
private static final MBeanNotificationInfo[] notifsInfo = {
new MBeanNotificationInfo(
types,
"javax.management.monitor.MonitorNotification",
"Notifications sent by the GaugeMonitor MBean")
};
// Flags needed to implement the hysteresis mechanism.
//
private static final int RISING = 0;
private static final int FALLING = 1;
private static final int RISING_OR_FALLING = 2;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Default constructor.
*/
public GaugeMonitor() {
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Starts the gauge monitor.
*/
public synchronized void start() {
if (isActive()) {
MONITOR_LOGGER.logp(Level.FINER, GaugeMonitor.class.getName(),
"start", "the monitor is already active");
return;
}
// Reset values.
//
for (ObservedObject o : observedObjects) {
final GaugeMonitorObservedObject gmo =
(GaugeMonitorObservedObject) o;
gmo.setStatus(RISING_OR_FALLING);
gmo.setPreviousScanGauge(null);
}
doStart();
}
/** {@collect.stats}
* Stops the gauge monitor.
*/
public synchronized void stop() {
doStop();
}
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the derived gauge of the specified object, if this object is
* contained in the set of observed MBeans, or <code>null</code> otherwise.
*
* @param object the name of the MBean.
*
* @return The derived gauge of the specified object.
*
*/
@Override
public synchronized Number getDerivedGauge(ObjectName object) {
return (Number) super.getDerivedGauge(object);
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the specified object, if
* this object is contained in the set of observed MBeans, or
* <code>0</code> otherwise.
*
* @param object the name of the object whose derived gauge
* timestamp is to be returned.
*
* @return The derived gauge timestamp of the specified object.
*
*/
@Override
public synchronized long getDerivedGaugeTimeStamp(ObjectName object) {
return super.getDerivedGaugeTimeStamp(object);
}
/** {@collect.stats}
* Returns the derived gauge of the first object in the set of
* observed MBeans.
*
* @return The derived gauge.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGauge(ObjectName)}
*/
@Deprecated
public synchronized Number getDerivedGauge() {
if (observedObjects.isEmpty()) {
return null;
} else {
return (Number) observedObjects.get(0).getDerivedGauge();
}
}
/** {@collect.stats}
* Gets the derived gauge timestamp of the first object in the set
* of observed MBeans.
*
* @return The derived gauge timestamp.
*
* @deprecated As of JMX 1.2, replaced by
* {@link #getDerivedGaugeTimeStamp(ObjectName)}
*/
@Deprecated
public synchronized long getDerivedGaugeTimeStamp() {
if (observedObjects.isEmpty()) {
return 0;
} else {
return observedObjects.get(0).getDerivedGaugeTimeStamp();
}
}
/** {@collect.stats}
* Gets the high threshold value common to all observed MBeans.
*
* @return The high threshold value.
*
* @see #setThresholds
*/
public synchronized Number getHighThreshold() {
return highThreshold;
}
/** {@collect.stats}
* Gets the low threshold value common to all observed MBeans.
*
* @return The low threshold value.
*
* @see #setThresholds
*/
public synchronized Number getLowThreshold() {
return lowThreshold;
}
/** {@collect.stats}
* Sets the high and the low threshold values common to all
* observed MBeans.
*
* @param highValue The high threshold value.
* @param lowValue The low threshold value.
*
* @exception IllegalArgumentException The specified high/low
* threshold is null or the low threshold is greater than the high
* threshold or the high threshold and the low threshold are not
* of the same type.
*
* @see #getHighThreshold
* @see #getLowThreshold
*/
public synchronized void setThresholds(Number highValue, Number lowValue)
throws IllegalArgumentException {
if ((highValue == null) || (lowValue == null)) {
throw new IllegalArgumentException("Null threshold value");
}
if (highValue.getClass() != lowValue.getClass()) {
throw new IllegalArgumentException("Different type " +
"threshold values");
}
if (isFirstStrictlyGreaterThanLast(lowValue, highValue,
highValue.getClass().getName())) {
throw new IllegalArgumentException("High threshold less than " +
"low threshold");
}
if (highThreshold.equals(highValue) && lowThreshold.equals(lowValue))
return;
highThreshold = highValue;
lowThreshold = lowValue;
// Reset values.
//
int index = 0;
for (ObservedObject o : observedObjects) {
resetAlreadyNotified(o, index++, THRESHOLD_ERROR_NOTIFIED);
final GaugeMonitorObservedObject gmo =
(GaugeMonitorObservedObject) o;
gmo.setStatus(RISING_OR_FALLING);
}
}
/** {@collect.stats}
* Gets the high notification's on/off switch value common to all
* observed MBeans.
*
* @return <CODE>true</CODE> if the gauge monitor notifies when
* exceeding the high threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotifyHigh
*/
public synchronized boolean getNotifyHigh() {
return notifyHigh;
}
/** {@collect.stats}
* Sets the high notification's on/off switch value common to all
* observed MBeans.
*
* @param value The high notification's on/off switch value.
*
* @see #getNotifyHigh
*/
public synchronized void setNotifyHigh(boolean value) {
if (notifyHigh == value)
return;
notifyHigh = value;
}
/** {@collect.stats}
* Gets the low notification's on/off switch value common to all
* observed MBeans.
*
* @return <CODE>true</CODE> if the gauge monitor notifies when
* exceeding the low threshold, <CODE>false</CODE> otherwise.
*
* @see #setNotifyLow
*/
public synchronized boolean getNotifyLow() {
return notifyLow;
}
/** {@collect.stats}
* Sets the low notification's on/off switch value common to all
* observed MBeans.
*
* @param value The low notification's on/off switch value.
*
* @see #getNotifyLow
*/
public synchronized void setNotifyLow(boolean value) {
if (notifyLow == value)
return;
notifyLow = value;
}
/** {@collect.stats}
* Gets the difference mode flag value common to all observed MBeans.
*
* @return <CODE>true</CODE> if the difference mode is used,
* <CODE>false</CODE> otherwise.
*
* @see #setDifferenceMode
*/
public synchronized boolean getDifferenceMode() {
return differenceMode;
}
/** {@collect.stats}
* Sets the difference mode flag value common to all observed MBeans.
*
* @param value The difference mode flag value.
*
* @see #getDifferenceMode
*/
public synchronized void setDifferenceMode(boolean value) {
if (differenceMode == value)
return;
differenceMode = value;
// Reset values.
//
for (ObservedObject o : observedObjects) {
final GaugeMonitorObservedObject gmo =
(GaugeMonitorObservedObject) o;
gmo.setStatus(RISING_OR_FALLING);
gmo.setPreviousScanGauge(null);
}
}
/** {@collect.stats}
* Returns a <CODE>NotificationInfo</CODE> object containing the
* name of the Java class of the notification and the notification
* types sent by the gauge monitor.
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
return notifsInfo.clone();
}
/*
* ------------------------------------------
* PRIVATE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Updates the derived gauge attribute of the observed object.
*
* @param scanGauge The value of the observed attribute.
* @param o The observed object.
* @return <CODE>true</CODE> if the derived gauge value is valid,
* <CODE>false</CODE> otherwise. The derived gauge value is
* invalid when the differenceMode flag is set to
* <CODE>true</CODE> and it is the first notification (so we
* haven't 2 consecutive values to update the derived gauge).
*/
private synchronized boolean updateDerivedGauge(
Object scanGauge, GaugeMonitorObservedObject o) {
boolean is_derived_gauge_valid;
// The gauge difference mode is used.
//
if (differenceMode) {
// The previous scan gauge has been initialized.
//
if (o.getPreviousScanGauge() != null) {
setDerivedGaugeWithDifference((Number)scanGauge, o);
is_derived_gauge_valid = true;
}
// The previous scan gauge has not been initialized.
// We cannot update the derived gauge...
//
else {
is_derived_gauge_valid = false;
}
o.setPreviousScanGauge((Number)scanGauge);
}
// The gauge difference mode is not used.
//
else {
o.setDerivedGauge((Number)scanGauge);
is_derived_gauge_valid = true;
}
return is_derived_gauge_valid;
}
/** {@collect.stats}
* Updates the notification attribute of the observed object
* and notifies the listeners only once if the notify flag
* is set to <CODE>true</CODE>.
* @param o The observed object.
*/
private synchronized MonitorNotification updateNotifications(
GaugeMonitorObservedObject o) {
MonitorNotification n = null;
// Send high notification if notifyHigh is true.
// Send low notification if notifyLow is true.
//
if (o.getStatus() == RISING_OR_FALLING) {
if (isFirstGreaterThanLast((Number)o.getDerivedGauge(),
highThreshold,
o.getType())) {
if (notifyHigh) {
n = new MonitorNotification(
THRESHOLD_HIGH_VALUE_EXCEEDED,
this,
0,
0,
"",
null,
null,
null,
highThreshold);
}
o.setStatus(FALLING);
} else if (isFirstGreaterThanLast(lowThreshold,
(Number)o.getDerivedGauge(),
o.getType())) {
if (notifyLow) {
n = new MonitorNotification(
THRESHOLD_LOW_VALUE_EXCEEDED,
this,
0,
0,
"",
null,
null,
null,
lowThreshold);
}
o.setStatus(RISING);
}
} else {
if (o.getStatus() == RISING) {
if (isFirstGreaterThanLast((Number)o.getDerivedGauge(),
highThreshold,
o.getType())) {
if (notifyHigh) {
n = new MonitorNotification(
THRESHOLD_HIGH_VALUE_EXCEEDED,
this,
0,
0,
"",
null,
null,
null,
highThreshold);
}
o.setStatus(FALLING);
}
} else if (o.getStatus() == FALLING) {
if (isFirstGreaterThanLast(lowThreshold,
(Number)o.getDerivedGauge(),
o.getType())) {
if (notifyLow) {
n = new MonitorNotification(
THRESHOLD_LOW_VALUE_EXCEEDED,
this,
0,
0,
"",
null,
null,
null,
lowThreshold);
}
o.setStatus(RISING);
}
}
}
return n;
}
/** {@collect.stats}
* Sets the derived gauge when the differenceMode flag is set to
* <CODE>true</CODE>. Both integer and floating-point types are
* allowed.
*
* @param scanGauge The value of the observed attribute.
* @param o The observed object.
*/
private synchronized void setDerivedGaugeWithDifference(
Number scanGauge, GaugeMonitorObservedObject o) {
Number prev = o.getPreviousScanGauge();
Number der;
switch (o.getType()) {
case INTEGER:
der = new Integer(((Integer)scanGauge).intValue() -
((Integer)prev).intValue());
break;
case BYTE:
der = new Byte((byte)(((Byte)scanGauge).byteValue() -
((Byte)prev).byteValue()));
break;
case SHORT:
der = new Short((short)(((Short)scanGauge).shortValue() -
((Short)prev).shortValue()));
break;
case LONG:
der = new Long(((Long)scanGauge).longValue() -
((Long)prev).longValue());
break;
case FLOAT:
der = new Float(((Float)scanGauge).floatValue() -
((Float)prev).floatValue());
break;
case DOUBLE:
der = new Double(((Double)scanGauge).doubleValue() -
((Double)prev).doubleValue());
break;
default:
// Should never occur...
MONITOR_LOGGER.logp(Level.FINEST, GaugeMonitor.class.getName(),
"setDerivedGaugeWithDifference",
"the threshold type is invalid");
return;
}
o.setDerivedGauge(der);
}
/** {@collect.stats}
* Tests if the first specified Number is greater than or equal to
* the last. Both integer and floating-point types are allowed.
*
* @param greater The first Number to compare with the second.
* @param less The second Number to compare with the first.
* @param type The number type.
* @return <CODE>true</CODE> if the first specified Number is
* greater than or equal to the last, <CODE>false</CODE>
* otherwise.
*/
private boolean isFirstGreaterThanLast(Number greater,
Number less,
NumericalType type) {
switch (type) {
case INTEGER:
case BYTE:
case SHORT:
case LONG:
return (greater.longValue() >= less.longValue());
case FLOAT:
case DOUBLE:
return (greater.doubleValue() >= less.doubleValue());
default:
// Should never occur...
MONITOR_LOGGER.logp(Level.FINEST, GaugeMonitor.class.getName(),
"isFirstGreaterThanLast",
"the threshold type is invalid");
return false;
}
}
/** {@collect.stats}
* Tests if the first specified Number is strictly greater than the last.
* Both integer and floating-point types are allowed.
*
* @param greater The first Number to compare with the second.
* @param less The second Number to compare with the first.
* @param className The number class name.
* @return <CODE>true</CODE> if the first specified Number is
* strictly greater than the last, <CODE>false</CODE> otherwise.
*/
private boolean isFirstStrictlyGreaterThanLast(Number greater,
Number less,
String className) {
if (className.equals("java.lang.Integer") ||
className.equals("java.lang.Byte") ||
className.equals("java.lang.Short") ||
className.equals("java.lang.Long")) {
return (greater.longValue() > less.longValue());
}
else if (className.equals("java.lang.Float") ||
className.equals("java.lang.Double")) {
return (greater.doubleValue() > less.doubleValue());
}
else {
// Should never occur...
MONITOR_LOGGER.logp(Level.FINEST, GaugeMonitor.class.getName(),
"isFirstStrictlyGreaterThanLast",
"the threshold type is invalid");
return false;
}
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Factory method for ObservedObject creation.
*
* @since 1.6
*/
@Override
ObservedObject createObservedObject(ObjectName object) {
final GaugeMonitorObservedObject gmo =
new GaugeMonitorObservedObject(object);
gmo.setStatus(RISING_OR_FALLING);
gmo.setPreviousScanGauge(null);
return gmo;
}
/** {@collect.stats}
* This method globally sets the derived gauge type for the given
* "object" and "attribute" after checking that the type of the
* supplied observed attribute value is one of the value types
* supported by this monitor.
*/
@Override
synchronized boolean isComparableTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
final GaugeMonitorObservedObject o =
(GaugeMonitorObservedObject) getObservedObject(object);
if (o == null)
return false;
// Check that the observed attribute is either of type
// "Integer" or "Float".
//
if (value instanceof Integer) {
o.setType(INTEGER);
} else if (value instanceof Byte) {
o.setType(BYTE);
} else if (value instanceof Short) {
o.setType(SHORT);
} else if (value instanceof Long) {
o.setType(LONG);
} else if (value instanceof Float) {
o.setType(FLOAT);
} else if (value instanceof Double) {
o.setType(DOUBLE);
} else {
return false;
}
return true;
}
@Override
synchronized Comparable<?> getDerivedGaugeFromComparable(
ObjectName object,
String attribute,
Comparable<?> value) {
final GaugeMonitorObservedObject o =
(GaugeMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// Update the derived gauge attributes and check the
// validity of the new value. The derived gauge value
// is invalid when the differenceMode flag is set to
// true and it is the first notification, i.e. we
// haven't got 2 consecutive values to update the
// derived gauge.
//
o.setDerivedGaugeValid(updateDerivedGauge(value, o));
return (Comparable<?>) o.getDerivedGauge();
}
@Override
synchronized void onErrorNotification(MonitorNotification notification) {
final GaugeMonitorObservedObject o = (GaugeMonitorObservedObject)
getObservedObject(notification.getObservedObject());
if (o == null)
return;
// Reset values.
//
o.setStatus(RISING_OR_FALLING);
o.setPreviousScanGauge(null);
}
@Override
synchronized MonitorNotification buildAlarmNotification(
ObjectName object,
String attribute,
Comparable<?> value) {
final GaugeMonitorObservedObject o =
(GaugeMonitorObservedObject) getObservedObject(object);
if (o == null)
return null;
// Notify the listeners if the updated derived
// gauge value is valid.
//
final MonitorNotification alarm;
if (o.getDerivedGaugeValid())
alarm = updateNotifications(o);
else
alarm = null;
return alarm;
}
/** {@collect.stats}
* Tests if the threshold high and threshold low are both of the
* same type as the gauge. Both integer and floating-point types
* are allowed.
*
* Note:
* If the optional lowThreshold or highThreshold have not been
* initialized, their default value is an Integer object with
* a value equal to zero.
*
* @param object The observed object.
* @param attribute The observed attribute.
* @param value The sample value.
* @return <CODE>true</CODE> if type is the same,
* <CODE>false</CODE> otherwise.
*/
@Override
synchronized boolean isThresholdTypeValid(ObjectName object,
String attribute,
Comparable<?> value) {
final GaugeMonitorObservedObject o =
(GaugeMonitorObservedObject) getObservedObject(object);
if (o == null)
return false;
Class<? extends Number> c = classForType(o.getType());
return (isValidForType(highThreshold, c) &&
isValidForType(lowThreshold, c));
}
}
|
Java
|
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* This class is used by the query-building mechanism to represent
* disjunctions of relational expressions.
* @serial include
*
* @since 1.5
*/
class OrQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = 2962973084421716523L;
/** {@collect.stats}
* @serial The left query expression
*/
private QueryExp exp1;
/** {@collect.stats}
* @serial The right query expression
*/
private QueryExp exp2;
/** {@collect.stats}
* Basic Constructor.
*/
public OrQueryExp() {
}
/** {@collect.stats}
* Creates a new OrQueryExp with the specified ValueExps
*/
public OrQueryExp(QueryExp q1, QueryExp q2) {
exp1 = q1;
exp2 = q2;
}
/** {@collect.stats}
* Returns the left query expression.
*/
public QueryExp getLeftExp() {
return exp1;
}
/** {@collect.stats}
* Returns the right query expression.
*/
public QueryExp getRightExp() {
return exp2;
}
/** {@collect.stats}
* Applies the OrQueryExp on a MBean.
*
* @param name The name of the MBean on which the OrQueryExp will be applied.
*
* @return True if the query was successfully applied to the MBean, false otherwise.
*
*
* @exception BadStringOperationException The string passed to the method is invalid.
* @exception BadBinaryOpValueExpException The expression passed to the method is invalid.
* @exception BadAttributeValueExpException The attribute value passed to the method is invalid.
*/
public boolean apply(ObjectName name) throws BadStringOperationException,
BadBinaryOpValueExpException, BadAttributeValueExpException,
InvalidApplicationException {
return exp1.apply(name) || exp2.apply(name);
}
/** {@collect.stats}
* Returns a string representation of this AndQueryExp
*/
public String toString() {
return "(" + exp1 + ") or (" + exp2 + ")";
}
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import javax.imageio.metadata.IIOMetadata;
/** {@collect.stats}
* An interface providing metadata transcoding capability.
*
* <p> Any image may be transcoded (written to a different format
* than the one it was originally stored in) simply by performing
* a read operation followed by a write operation. However, loss
* of data may occur in this process due to format differences.
*
* <p> In general, the best results will be achieved when
* format-specific metadata objects can be created to encapsulate as
* much information about the image and its associated metadata as
* possible, in terms that are understood by the specific
* <code>ImageWriter</code> used to perform the encoding.
*
* <p> An <code>ImageTranscoder</code> may be used to convert the
* <code>IIOMetadata</code> objects supplied by the
* <code>ImageReader</code> (representing per-stream and per-image
* metadata) into corresponding objects suitable for encoding by a
* particular <code>ImageWriter</code>. In the case where the methods
* of this interface are being called directly on an
* <code>ImageWriter</code>, the output will be suitable for that
* writer.
*
* <p> The internal details of converting an <code>IIOMetadata</code>
* object into a writer-specific format will vary according to the
* context of the operation. Typically, an <code>ImageWriter</code>
* will inspect the incoming object to see if it implements additional
* interfaces with which the writer is familiar. This might be the
* case, for example, if the object was obtained by means of a read
* operation on a reader plug-in written by the same vendor as the
* writer. In this case, the writer may access the incoming object by
* means of its plug-in specific interfaces. In this case, the
* re-encoding may be close to lossless if the image file format is
* kept constant. If the format is changing, the writer may still
* attempt to preserve as much information as possible.
*
* <p> If the incoming object does not implement any additional
* interfaces known to the writer, the writer has no choice but to
* access it via the standard <code>IIOMetadata</code> interfaces such
* as the tree view provided by <code>IIOMetadata.getAsTree</code>.
* In this case, there is likely to be significant loss of
* information.
*
* <p> An independent <code>ImageTranscoder</code> essentially takes
* on the same role as the writer plug-in in the above examples. It
* must be familiar with the private interfaces used by both the
* reader and writer plug-ins, and manually instantiate an object that
* will be usable by the writer. The resulting metadata objects may
* be used by the writer directly.
*
* <p> No independent implementations of <code>ImageTranscoder</code>
* are provided as part of the standard API. Instead, the intention
* of this interface is to provide a way for implementations to be
* created and discovered by applications as the need arises.
*
*/
public interface ImageTranscoder {
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object that may be used for
* encoding and optionally modified using its document interfaces
* or other interfaces specific to the writer plug-in that will be
* used for encoding.
*
* <p> An optional <code>ImageWriteParam</code> may be supplied
* for cases where it may affect the structure of the stream
* metadata.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not understood by this writer or
* transcoder, they will be ignored.
*
* @param inData an <code>IIOMetadata</code> object representing
* stream metadata, used to initialize the state of the returned
* object.
* @param param an <code>ImageWriteParam</code> that will be used to
* encode the image, or <code>null</code>.
*
* @return an <code>IIOMetadata</code> object, or
* <code>null</code> if the plug-in does not provide metadata
* encoding capabilities.
*
* @exception IllegalArgumentException if <code>inData</code> is
* <code>null</code>.
*/
IIOMetadata convertStreamMetadata(IIOMetadata inData,
ImageWriteParam param);
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object that may be used for
* encoding and optionally modified using its document interfaces
* or other interfaces specific to the writer plug-in that will be
* used for encoding.
*
* <p> An optional <code>ImageWriteParam</code> may be supplied
* for cases where it may affect the structure of the image
* metadata.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not understood by this writer or
* transcoder, they will be ignored.
*
* @param inData an <code>IIOMetadata</code> object representing
* image metadata, used to initialize the state of the returned
* object.
* @param imageType an <code>ImageTypeSpecifier</code> indicating
* the layout and color information of the image with which the
* metadata will be associated.
* @param param an <code>ImageWriteParam</code> that will be used to
* encode the image, or <code>null</code>.
*
* @return an <code>IIOMetadata</code> object,
* or <code>null</code> if the plug-in does not provide
* metadata encoding capabilities.
*
* @exception IllegalArgumentException if either of
* <code>inData</code> or <code>imageType</code> is
* <code>null</code>.
*/
IIOMetadata convertImageMetadata(IIOMetadata inData,
ImageTypeSpecifier imageType,
ImageWriteParam param);
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import java.util.Locale;
import javax.imageio.ImageTypeSpecifier;
/** {@collect.stats}
* An object describing the structure of metadata documents returned
* from <code>IIOMetadata.getAsTree</code> and passed to
* <code>IIOMetadata.setFromTree</code> and <code>mergeTree</code>.
* Document structures are described by a set of constraints on the
* type and number of child elements that may belong to a given parent
* element type, the names, types, and values of attributes that may
* belong to an element, and the type and values of
* <code>Object</code> reference that may be stored at a node.
*
* <p> N.B: classes that implement this interface should contain a
* method declared as <code>public static getInstance()</code> which
* returns an instance of the class. Commonly, an implentation will
* construct only a single instance and cache it for future
* invocations of <code>getInstance</code>.
*
* <p> The structures that may be described by this class are a subset
* of those expressible using XML document type definitions (DTDs),
* with the addition of some basic information on the datatypes of
* attributes and the ability to store an <code>Object</code>
* reference within a node. In the future, XML Schemas could be used
* to represent these structures, and many others.
*
* <p> The differences between
* <code>IIOMetadataFormat</code>-described structures and DTDs are as
* follows:
*
* <ul>
* <li> Elements may not contain text or mix text with embedded
* tags.
*
* <li> The children of an element must conform to one of a few simple
* patterns, described in the documentation for the
* <code>CHILD_*</code> constants;
*
* <li> The in-memory representation of an elements may contain a
* reference to an <code>Object</code>. There is no provision for
* representing such objects textually.
* </ul>
*
*/
public interface IIOMetadataFormat {
// Child policies
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element may not have any children. In other words, it
* is required to be a leaf node.
*/
int CHILD_POLICY_EMPTY = 0;
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element must have a single instance of each of its
* legal child elements, in order. In DTD terms, the contents of
* the element are defined by a sequence <code>a,b,c,d,...</code>.
*/
int CHILD_POLICY_ALL = 1;
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element must have zero or one instance of each of its
* legal child elements, in order. In DTD terms, the contents of
* the element are defined by a sequence
* <code>a?,b?,c?,d?,...</code>.
*/
int CHILD_POLICY_SOME = 2;
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element must have zero or one children, selected from
* among its legal child elements. In DTD terms, the contents of
* the element are defined by a selection
* <code>a|b|c|d|...</code>.
*/
int CHILD_POLICY_CHOICE = 3;
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element must have a sequence of instances of any of its
* legal child elements. In DTD terms, the contents of the
* element are defined by a sequence <code>(a|b|c|d|...)*</code>.
*/
int CHILD_POLICY_SEQUENCE = 4;
/** {@collect.stats}
* A constant returned by <code>getChildPolicy</code> to indicate
* that an element must have zero or more instances of its unique
* legal child element. In DTD terms, the contents of the element
* are defined by a starred expression <code>a*</code>.
*/
int CHILD_POLICY_REPEAT = 5;
/** {@collect.stats}
* The largest valid <code>CHILD_POLICY_*</code> constant,
* to be used for range checks.
*/
int CHILD_POLICY_MAX = CHILD_POLICY_REPEAT;
/** {@collect.stats}
* A constant returned by <code>getObjectValueType</code> to
* indicate the absence of a user object.
*/
int VALUE_NONE = 0;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set a single, arbitrary value.
*/
int VALUE_ARBITRARY = 1;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set a range of values. Both the minimum
* and maximum values of the range are exclusive. It is
* recommended that ranges of integers be inclusive on both ends,
* and that exclusive ranges be used only for floating-point data.
*
* @see #VALUE_RANGE_MIN_MAX_INCLUSIVE
*/
int VALUE_RANGE = 2;
/** {@collect.stats}
* A value that may be or'ed with <code>VALUE_RANGE</code> to
* obtain <code>VALUE_RANGE_MIN_INCLUSIVE</code>, and with
* <code>VALUE_RANGE_MAX_INCLUSIVE</code> to obtain
* <code>VALUE_RANGE_MIN_MAX_INCLUSIVE</code>.
*
* <p> Similarly, the value may be and'ed with the value of
* <code>getAttributeValueType</code>or
* <code>getObjectValueType</code> to determine if the minimum
* value of the range is inclusive.
*/
int VALUE_RANGE_MIN_INCLUSIVE_MASK = 4;
/** {@collect.stats}
* A value that may be or'ed with <code>VALUE_RANGE</code> to
* obtain <code>VALUE_RANGE_MAX_INCLUSIVE</code>, and with
* <code>VALUE_RANGE_MIN_INCLUSIVE</code> to obtain
* <code>VALUE_RANGE_MIN_MAX_INCLUSIVE</code>.
*
* <p> Similarly, the value may be and'ed with the value of
* <code>getAttributeValueType</code>or
* <code>getObjectValueType</code> to determine if the maximum
* value of the range is inclusive.
*/
int VALUE_RANGE_MAX_INCLUSIVE_MASK = 8;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set to a range of values. The minimum
* (but not the maximum) value of the range is inclusive.
*/
int VALUE_RANGE_MIN_INCLUSIVE = VALUE_RANGE |
VALUE_RANGE_MIN_INCLUSIVE_MASK;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set to a range of values. The maximum
* (but not the minimum) value of the range is inclusive.
*/
int VALUE_RANGE_MAX_INCLUSIVE = VALUE_RANGE |
VALUE_RANGE_MAX_INCLUSIVE_MASK;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set a range of values. Both the minimum
* and maximum values of the range are inclusive. It is
* recommended that ranges of integers be inclusive on both ends,
* and that exclusive ranges be used only for floating-point data.
*/
int VALUE_RANGE_MIN_MAX_INCLUSIVE =
VALUE_RANGE |
VALUE_RANGE_MIN_INCLUSIVE_MASK |
VALUE_RANGE_MAX_INCLUSIVE_MASK;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set one of a number of enumerated values.
* In the case of attributes, these values are
* <code>String</code>s; for objects, they are
* <code>Object</code>s implementing a given class or interface.
*
* <p> Attribute values of type <code>DATATYPE_BOOLEAN</code>
* should be marked as enumerations.
*/
int VALUE_ENUMERATION = 16;
/** {@collect.stats}
* A constant returned by <code>getAttributeValueType</code> and
* <code>getObjectValueType</code> to indicate that the attribute
* or user object may be set to a list or array of values. In the
* case of attributes, the list will consist of
* whitespace-separated values within a <code>String</code>; for
* objects, an array will be used.
*/
int VALUE_LIST = 32;
/** {@collect.stats}
* A constant returned by <code>getAttributeDataType</code>
* indicating that the value of an attribute is a general Unicode
* string.
*/
int DATATYPE_STRING = 0;
/** {@collect.stats}
* A constant returned by <code>getAttributeDataType</code>
* indicating that the value of an attribute is one of 'true' or
* 'false'.
*/
int DATATYPE_BOOLEAN = 1;
/** {@collect.stats}
* A constant returned by <code>getAttributeDataType</code>
* indicating that the value of an attribute is a string
* representation of an integer.
*/
int DATATYPE_INTEGER = 2;
/** {@collect.stats}
* A constant returned by <code>getAttributeDataType</code>
* indicating that the value of an attribute is a string
* representation of a decimal floating-point number.
*/
int DATATYPE_FLOAT = 3;
/** {@collect.stats}
* A constant returned by <code>getAttributeDataType</code>
* indicating that the value of an attribute is a string
* representation of a double-precision decimal floating-point
* number.
*/
int DATATYPE_DOUBLE = 4;
// Root
/** {@collect.stats}
* Returns the name of the root element of the format.
*
* @return a <code>String</code>.
*/
String getRootName();
// Multiplicity
/** {@collect.stats}
* Returns <code>true</code> if the element (and the subtree below
* it) is allowed to appear in a metadata document for an image of
* the given type, defined by an <code>ImageTypeSpecifier</code>.
* For example, a metadata document format might contain an
* element that describes the primary colors of the image, which
* would not be allowed when writing a grayscale image.
*
* @param elementName the name of the element being queried.
* @param imageType an <code>ImageTypeSpecifier</code> indicating
* the type of the image that will be associated with the
* metadata.
*
* @return <code>true</code> if the node is meaningful for images
* of the given type.
*/
boolean canNodeAppear(String elementName, ImageTypeSpecifier imageType);
/** {@collect.stats}
* Returns the minimum number of children of the named element
* with child policy <code>CHILD_POLICY_REPEAT</code>. For
* example, an element representing color primary information
* might be required to have at least 3 children, one for each
* primay.
*
* @param elementName the name of the element being queried.
*
* @return an <code>int</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element does
* not have a child policy of <code>CHILD_POLICY_REPEAT</code>.
*/
int getElementMinChildren(String elementName);
/** {@collect.stats}
* Returns the maximum number of children of the named element
* with child policy <code>CHILD_POLICY_REPEAT</code>. For
* example, an element representing an entry in an 8-bit color
* palette might be allowed to repeat up to 256 times. A value of
* <code>Integer.MAX_VALUE</code> may be used to specify that
* there is no upper bound.
*
* @param elementName the name of the element being queried.
*
* @return an <code>int</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element does
* not have a child policy of <code>CHILD_POLICY_REPEAT</code>.
*/
int getElementMaxChildren(String elementName);
/** {@collect.stats}
* Returns a <code>String</code> containing a description of the
* named element, or <code>null</code>. The desciption will be
* localized for the supplied <code>Locale</code> if possible.
*
* <p> If <code>locale</code> is <code>null</code>, the current
* default <code>Locale</code> returned by <code>Locale.getLocale</code>
* will be used.
*
* @param elementName the name of the element.
* @param locale the <code>Locale</code> for which localization
* will be attempted.
*
* @return the element description.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
*/
String getElementDescription(String elementName, Locale locale);
// Children
/** {@collect.stats}
* Returns one of the constants starting with
* <code>CHILD_POLICY_</code>, indicating the legal pattern of
* children for the named element.
*
* @param elementName the name of the element being queried.
*
* @return one of the <code>CHILD_POLICY_*</code> constants.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
*/
int getChildPolicy(String elementName);
/** {@collect.stats}
* Returns an array of <code>String</code>s indicating the names
* of the element which are allowed to be children of the named
* element, in the order in which they should appear. If the
* element cannot have children, <code>null</code> is returned.
*
* @param elementName the name of the element being queried.
*
* @return an array of <code>String</code>s, or null.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
*/
String[] getChildNames(String elementName);
// Attributes
/** {@collect.stats}
* Returns an array of <code>String</code>s listing the names of
* the attributes that may be associated with the named element.
*
* @param elementName the name of the element being queried.
*
* @return an array of <code>String</code>s.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
*/
String[] getAttributeNames(String elementName);
/** {@collect.stats}
* Returns one of the constants starting with <code>VALUE_</code>,
* indicating whether the values of the given attribute within the
* named element are arbitrary, constrained to lie within a
* specified range, constrained to be one of a set of enumerated
* values, or are a whitespace-separated list of arbitrary values.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return one of the <code>VALUE_*</code> constants.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*/
int getAttributeValueType(String elementName, String attrName);
/** {@collect.stats}
* Returns one of the constants starting with
* <code>DATATYPE_</code>, indicating the format and
* interpretation of the value of the given attribute within th
* enamed element. If <code>getAttributeValueType</code> returns
* <code>VALUE_LIST</code>, then the legal value is a
* whitespace-spearated list of values of the returned datatype.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return one of the <code>DATATYPE_*</code> constants.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*/
int getAttributeDataType(String elementName, String attrName);
/** {@collect.stats}
* Returns <code>true</code> if the named attribute must be
* present within the named element.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return <code>true</code> if the attribut must be present.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*/
boolean isAttributeRequired(String elementName, String attrName);
/** {@collect.stats}
* Returns the default value of the named attribute, if it is not
* explictly present within the named element, as a
* <code>String</code>, or <code>null</code> if no default value
* is available.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return a <code>String</code> containing the default value, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*/
String getAttributeDefaultValue(String elementName, String attrName);
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the legal
* enumerated values for the given attribute within the named
* element. This method should only be called if
* <code>getAttributeValueType</code> returns
* <code>VALUE_ENUMERATION</code>.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return an array of <code>String</code>s.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
* @exception IllegalArgumentException if the given attribute is
* not defined as an enumeration.
*/
String[] getAttributeEnumerations(String elementName, String attrName);
/** {@collect.stats}
* Returns the minimum legal value for the attribute. Whether
* this value is inclusive or exclusive may be determined by the
* value of <code>getAttributeValueType</code>. The value is
* returned as a <code>String</code>; its interpretation is
* dependent on the value of <code>getAttributeDataType</code>.
* This method should only be called if
* <code>getAttributeValueType</code> returns
* <code>VALUE_RANGE_*</code>.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return a <code>String</code> containing the smallest legal
* value for the attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
* @exception IllegalArgumentException if the given attribute is
* not defined as a range.
*/
String getAttributeMinValue(String elementName, String attrName);
/** {@collect.stats}
* Returns the maximum legal value for the attribute. Whether
* this value is inclusive or exclusive may be determined by the
* value of <code>getAttributeValueType</code>. The value is
* returned as a <code>String</code>; its interpretation is
* dependent on the value of <code>getAttributeDataType</code>.
* This method should only be called if
* <code>getAttributeValueType</code> returns
* <code>VALUE_RANGE_*</code>.
*
* @param elementName the name of the element being queried, as a
* <code>String</code>.
* @param attrName the name of the attribute being queried.
*
* @return a <code>String</code> containing the largest legal
* value for the attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
* @exception IllegalArgumentException if the given attribute is
* not defined as a range.
*/
String getAttributeMaxValue(String elementName, String attrName);
/** {@collect.stats}
* Returns the minimum number of list items that may be used to
* define this attribute. The attribute itself is defined as a
* <code>String</code> containing multiple whitespace-separated
* items. This method should only be called if
* <code>getAttributeValueType</code> returns
* <code>VALUE_LIST</code>.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return the smallest legal number of list items for the
* attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
* @exception IllegalArgumentException if the given attribute is
* not defined as a list.
*/
int getAttributeListMinLength(String elementName, String attrName);
/** {@collect.stats}
* Returns the maximum number of list items that may be used to
* define this attribute. A value of
* <code>Integer.MAX_VALUE</code> may be used to specify that
* there is no upper bound. The attribute itself is defined as a
* <code>String</code> containing multiple whitespace-separated
* items. This method should only be called if
* <code>getAttributeValueType</code> returns
* <code>VALUE_LIST</code>.
*
* @param elementName the name of the element being queried.
* @param attrName the name of the attribute being queried.
*
* @return the largest legal number of list items for the
* attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
* @exception IllegalArgumentException if the given attribute is
* not defined as a list.
*/
int getAttributeListMaxLength(String elementName, String attrName);
/** {@collect.stats}
* Returns a <code>String</code> containing a description of the
* named attribute, or <code>null</code>. The desciption will be
* localized for the supplied <code>Locale</code> if possible.
*
* <p> If <code>locale</code> is <code>null</code>, the current
* default <code>Locale</code> returned by <code>Locale.getLocale</code>
* will be used.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute.
* @param locale the <code>Locale</code> for which localization
* will be attempted.
*
* @return the attribute description.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*/
String getAttributeDescription(String elementName, String attrName,
Locale locale);
// Object value
/** {@collect.stats}
* Returns one of the enumerated values starting with
* <code>VALUE_</code>, indicating the type of values
* (enumeration, range, or array) that are allowed for the
* <code>Object</code> reference. If no object value can be
* stored within the given element, the result of this method will
* be <code>VALUE_NONE</code>.
*
* <p> <code>Object</code> references whose legal values are
* defined as a range must implement the <code>Comparable</code>
* interface.
*
* @param elementName the name of the element being queried.
*
* @return one of the <code>VALUE_*</code> constants.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
*
* @see Comparable
*/
int getObjectValueType(String elementName);
/** {@collect.stats}
* Returns the <code>Class</code> type of the <code>Object</code>
* reference stored within the element. If this element may not
* contain an <code>Object</code> reference, an
* <code>IllegalArgumentException</code> will be thrown. If the
* class type is an array, this field indicates the underlying
* class type (<i>e.g</i>, for an array of <code>int</code>s, this
* method would return <code>int.class</code>).
*
* <p> <code>Object</code> references whose legal values are
* defined as a range must implement the <code>Comparable</code>
* interface.
*
* @param elementName the name of the element being queried.
*
* @return a <code>Class</code> object.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
*/
Class<?> getObjectClass(String elementName);
/** {@collect.stats}
* Returns an <code>Object</code>s containing the default
* value for the <code>Object</code> reference within
* the named element.
*
* @param elementName the name of the element being queried.
*
* @return an <code>Object</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
*/
Object getObjectDefaultValue(String elementName);
/** {@collect.stats}
* Returns an array of <code>Object</code>s containing the legal
* enumerated values for the <code>Object</code> reference within
* the named element. This method should only be called if
* <code>getObjectValueType</code> returns
* <code>VALUE_ENUMERATION</code>.
*
* <p> The <code>Object</code> associated with a node that accepts
* emuerated values must be equal to one of the values returned by
* this method, as defined by the <code>==</code> operator (as
* opposed to the <code>Object.equals</code> method).
*
* @param elementName the name of the element being queried.
*
* @return an array of <code>Object</code>s.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
* @exception IllegalArgumentException if the <code>Object</code>
* is not defined as an enumeration.
*/
Object[] getObjectEnumerations(String elementName);
/** {@collect.stats}
* Returns the minimum legal value for the <code>Object</code>
* reference within the named element. Whether this value is
* inclusive or exclusive may be determined by the value of
* <code>getObjectValueType</code>. This method should only be
* called if <code>getObjectValueType</code> returns one of the
* constants starting with <code>VALUE_RANGE</code>.
*
* @param elementName the name of the element being queried.
*
* @return the smallest legal value for the attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
* @exception IllegalArgumentException if the <code>Object</code>
* is not defined as a range.
*/
Comparable<?> getObjectMinValue(String elementName);
/** {@collect.stats}
* Returns the maximum legal value for the <code>Object</code>
* reference within the named element. Whether this value is
* inclusive or exclusive may be determined by the value of
* <code>getObjectValueType</code>. This method should only be
* called if <code>getObjectValueType</code> returns one of the
* constants starting with <code>VALUE_RANGE</code>.
*
* @return the smallest legal value for the attribute.
*
* @param elementName the name of the element being queried.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
* @exception IllegalArgumentException if the <code>Object</code>
* is not defined as a range.
*/
Comparable<?> getObjectMaxValue(String elementName);
/** {@collect.stats}
* Returns the minimum number of array elements that may be used
* to define the <code>Object</code> reference within the named
* element. This method should only be called if
* <code>getObjectValueType</code> returns
* <code>VALUE_LIST</code>.
*
* @param elementName the name of the element being queried.
*
* @return the smallest valid array length for the
* <code>Object</code> reference.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
* @exception IllegalArgumentException if the <code>Object</code> is not
* an array.
*/
int getObjectArrayMinLength(String elementName);
/** {@collect.stats}
* Returns the maximum number of array elements that may be used
* to define the <code>Object</code> reference within the named
* element. A value of <code>Integer.MAX_VALUE</code> may be used
* to specify that there is no upper bound. This method should
* only be called if <code>getObjectValueType</code> returns
* <code>VALUE_LIST</code>.
*
* @param elementName the name of the element being queried.
*
* @return the largest valid array length for the
* <code>Object</code> reference.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code> or is not a legal element name for this
* format.
* @exception IllegalArgumentException if the named element cannot
* contain an object value (<i>i.e.</i>, if
* <code>getObjectValueType(elementName) == VALUE_NONE</code>).
* @exception IllegalArgumentException if the <code>Object</code> is not
* an array.
*/
int getObjectArrayMaxLength(String elementName);
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import javax.imageio.IIOException;
import org.w3c.dom.Node;
/** {@collect.stats}
* An <code>IIOInvalidTreeException</code> is thrown when an attempt
* by an <code>IIOMetadata</code> object to parse a tree of
* <code>IIOMetadataNode</code>s fails. The node that led to the
* parsing error may be stored. As with any parsing error, the actual
* error may occur at a different point that that where it is
* detected. The node returned by <code>getOffendingNode</code>
* should merely be considered as a clue to the actual nature of the
* problem.
*
* @see IIOMetadata#setFromTree
* @see IIOMetadata#mergeTree
* @see IIOMetadataNode
*
*/
public class IIOInvalidTreeException extends IIOException {
/** {@collect.stats}
* The <code>Node</code> that led to the parsing error, or
* <code>null</code>.
*/
protected Node offendingNode = null;
/** {@collect.stats}
* Constructs an <code>IIOInvalidTreeException</code> with a
* message string and a reference to the <code>Node</code> that
* caused the parsing error.
*
* @param message a <code>String</code> containing the reason for
* the parsing failure.
* @param offendingNode the DOM <code>Node</code> that caused the
* exception, or <code>null</code>.
*/
public IIOInvalidTreeException(String message, Node offendingNode) {
super(message);
this.offendingNode = offendingNode;
}
/** {@collect.stats}
* Constructs an <code>IIOInvalidTreeException</code> with a
* message string, a reference to an exception that caused this
* exception, and a reference to the <code>Node</code> that caused
* the parsing error.
*
* @param message a <code>String</code> containing the reason for
* the parsing failure.
* @param cause the <code>Throwable</code> (<code>Error</code> or
* <code>Exception</code>) that caused this exception to occur,
* or <code>null</code>.
* @param offendingNode the DOM <code>Node</code> that caused the
* exception, or <code>null</code>.
*/
public IIOInvalidTreeException(String message, Throwable cause,
Node offendingNode) {
super(message, cause);
this.offendingNode = offendingNode;
}
/** {@collect.stats}
* Returns the <code>Node</code> that caused the error in parsing.
*
* @return the offending <code>Node</code>.
*/
public Node getOffendingNode() {
return offendingNode;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.imageio.ImageTypeSpecifier;
import com.sun.imageio.plugins.common.StandardMetadataFormat;
/** {@collect.stats}
* A concrete class providing a reusable implementation of the
* <code>IIOMetadataFormat</code> interface. In addition, a static
* instance representing the standard, plug-in neutral
* <code>javax_imageio_1.0</code> format is provided by the
* <code>getStandardFormatInstance</code> method.
*
* <p> In order to supply localized descriptions of elements and
* attributes, a <code>ResourceBundle</code> with a base name of
* <code>this.getClass().getName() + "Resources"</code> should be
* supplied via the usual mechanism used by
* <code>ResourceBundle.getBundle</code>. Briefly, the subclasser
* supplies one or more additional classes according to a naming
* convention (by default, the fully-qualified name of the subclass
* extending <code>IIMetadataFormatImpl</code>, plus the string
* "Resources", plus the country, language, and variant codes
* separated by underscores). At run time, calls to
* <code>getElementDescription</code> or
* <code>getAttributeDescription</code> will attempt to load such
* classes dynamically according to the supplied locale, and will use
* either the element name, or the element name followed by a '/'
* character followed by the attribute name as a key. This key will
* be supplied to the <code>ResourceBundle</code>'s
* <code>getString</code> method, and the resulting localized
* description of the node or attribute is returned.
*
* <p> The subclass may supply a different base name for the resource
* bundles using the <code>setResourceBaseName</code> method.
*
* <p> A subclass may choose its own localization mechanism, if so
* desired, by overriding the supplied implementations of
* <code>getElementDescription</code> and
* <code>getAttributeDescription</code>.
*
* @see ResourceBundle#getBundle(String,Locale)
*
*/
public abstract class IIOMetadataFormatImpl implements IIOMetadataFormat {
/** {@collect.stats}
* A <code>String</code> constant containing the standard format
* name, <code>"javax_imageio_1.0"</code>.
*/
public static final String standardMetadataFormatName =
"javax_imageio_1.0";
private static IIOMetadataFormat standardFormat = null;
private String resourceBaseName = this.getClass().getName() + "Resources";
private String rootName;
// Element name (String) -> Element
private HashMap elementMap = new HashMap();
class Element {
String elementName;
int childPolicy;
int minChildren = 0;
int maxChildren = 0;
// Child names (Strings)
List childList = new ArrayList();
// Parent names (Strings)
List parentList = new ArrayList();
// List of attribute names in the order they were added
List attrList = new ArrayList();
// Attr name (String) -> Attribute
Map attrMap = new HashMap();
ObjectValue objectValue;
}
class Attribute {
String attrName;
int valueType = VALUE_ARBITRARY;
int dataType;
boolean required;
String defaultValue = null;
// enumeration
List enumeratedValues;
// range
String minValue;
String maxValue;
// list
int listMinLength;
int listMaxLength;
}
class ObjectValue {
int valueType = VALUE_NONE;
Class classType = null;
Object defaultValue = null;
// Meaningful only if valueType == VALUE_ENUMERATION
List enumeratedValues = null;
// Meaningful only if valueType == VALUE_RANGE
Comparable minValue = null;
Comparable maxValue = null;
// Meaningful only if valueType == VALUE_LIST
int arrayMinLength = 0;
int arrayMaxLength = 0;
}
/** {@collect.stats}
* Constructs a blank <code>IIOMetadataFormatImpl</code> instance,
* with a given root element name and child policy (other than
* <code>CHILD_POLICY_REPEAT</code>). Additional elements, and
* their attributes and <code>Object</code> reference information
* may be added using the various <code>add</code> methods.
*
* @param rootName the name of the root element.
* @param childPolicy one of the <code>CHILD_POLICY_*</code> constants,
* other than <code>CHILD_POLICY_REPEAT</code>.
*
* @exception IllegalArgumentException if <code>rootName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>childPolicy</code> is
* not one of the predefined constants.
*/
public IIOMetadataFormatImpl(String rootName,
int childPolicy) {
if (rootName == null) {
throw new IllegalArgumentException("rootName == null!");
}
if (childPolicy < CHILD_POLICY_EMPTY ||
childPolicy > CHILD_POLICY_MAX ||
childPolicy == CHILD_POLICY_REPEAT) {
throw new IllegalArgumentException("Invalid value for childPolicy!");
}
this.rootName = rootName;
Element root = new Element();
root.elementName = rootName;
root.childPolicy = childPolicy;
elementMap.put(rootName, root);
}
/** {@collect.stats}
* Constructs a blank <code>IIOMetadataFormatImpl</code> instance,
* with a given root element name and a child policy of
* <code>CHILD_POLICY_REPEAT</code>. Additional elements, and
* their attributes and <code>Object</code> reference information
* may be added using the various <code>add</code> methods.
*
* @param rootName the name of the root element.
* @param minChildren the minimum number of children of the node.
* @param maxChildren the maximum number of children of the node.
*
* @exception IllegalArgumentException if <code>rootName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>minChildren</code>
* is negative or larger than <code>maxChildren</code>.
*/
public IIOMetadataFormatImpl(String rootName,
int minChildren,
int maxChildren) {
if (rootName == null) {
throw new IllegalArgumentException("rootName == null!");
}
if (minChildren < 0) {
throw new IllegalArgumentException("minChildren < 0!");
}
if (minChildren > maxChildren) {
throw new IllegalArgumentException("minChildren > maxChildren!");
}
Element root = new Element();
root.elementName = rootName;
root.childPolicy = CHILD_POLICY_REPEAT;
root.minChildren = minChildren;
root.maxChildren = maxChildren;
this.rootName = rootName;
elementMap.put(rootName, root);
}
/** {@collect.stats}
* Sets a new base name for locating <code>ResourceBundle</code>s
* containing descriptions of elements and attributes for this
* format.
*
* <p> Prior to the first time this method is called, the base
* name will be equal to <code>this.getClass().getName() +
* "Resources"</code>.
*
* @param resourceBaseName a <code>String</code> containg the new
* base name.
*
* @exception IllegalArgumentException if
* <code>resourceBaseName</code> is <code>null</code>.
*
* @see #getResourceBaseName
*/
protected void setResourceBaseName(String resourceBaseName) {
if (resourceBaseName == null) {
throw new IllegalArgumentException("resourceBaseName == null!");
}
this.resourceBaseName = resourceBaseName;
}
/** {@collect.stats}
* Returns the currently set base name for locating
* <code>ResourceBundle</code>s.
*
* @return a <code>String</code> containing the base name.
*
* @see #setResourceBaseName
*/
protected String getResourceBaseName() {
return resourceBaseName;
}
/** {@collect.stats}
* Utility method for locating an element.
*
* @param mustAppear if <code>true</code>, throw an
* <code>IllegalArgumentException</code> if no such node exists;
* if <code>false</code>, just return null.
*/
private Element getElement(String elementName, boolean mustAppear) {
if (mustAppear && (elementName == null)) {
throw new IllegalArgumentException("element name is null!");
}
Element element = (Element)elementMap.get(elementName);
if (mustAppear && (element == null)) {
throw new IllegalArgumentException("No such element: " +
elementName);
}
return element;
}
private Element getElement(String elementName) {
return getElement(elementName, true);
}
// Utility method for locating an attribute
private Attribute getAttribute(String elementName, String attrName) {
Element element = getElement(elementName);
Attribute attr = (Attribute)element.attrMap.get(attrName);
if (attr == null) {
throw new IllegalArgumentException("No such attribute \"" +
attrName + "\"!");
}
return attr;
}
// Setup
/** {@collect.stats}
* Adds a new element type to this metadata document format with a
* child policy other than <code>CHILD_POLICY_REPEAT</code>.
*
* @param elementName the name of the new element.
* @param parentName the name of the element that will be the
* parent of the new element.
* @param childPolicy one of the <code>CHILD_POLICY_*</code>
* constants, other than <code>CHILD_POLICY_REPEAT</code>,
* indicating the child policy of the new element.
*
* @exception IllegalArgumentException if <code>parentName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>childPolicy</code>
* is not one of the predefined constants.
*/
protected void addElement(String elementName,
String parentName,
int childPolicy) {
Element parent = getElement(parentName);
if (childPolicy < CHILD_POLICY_EMPTY ||
childPolicy > CHILD_POLICY_MAX ||
childPolicy == CHILD_POLICY_REPEAT) {
throw new IllegalArgumentException
("Invalid value for childPolicy!");
}
Element element = new Element();
element.elementName = elementName;
element.childPolicy = childPolicy;
parent.childList.add(elementName);
element.parentList.add(parentName);
elementMap.put(elementName, element);
}
/** {@collect.stats}
* Adds a new element type to this metadata document format with a
* child policy of <code>CHILD_POLICY_REPEAT</code>.
*
* @param elementName the name of the new element.
* @param parentName the name of the element that will be the
* parent of the new element.
* @param minChildren the minimum number of children of the node.
* @param maxChildren the maximum number of children of the node.
*
* @exception IllegalArgumentException if <code>parentName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>minChildren</code>
* is negative or larger than <code>maxChildren</code>.
*/
protected void addElement(String elementName,
String parentName,
int minChildren,
int maxChildren) {
Element parent = getElement(parentName);
if (minChildren < 0) {
throw new IllegalArgumentException("minChildren < 0!");
}
if (minChildren > maxChildren) {
throw new IllegalArgumentException("minChildren > maxChildren!");
}
Element element = new Element();
element.elementName = elementName;
element.childPolicy = CHILD_POLICY_REPEAT;
element.minChildren = minChildren;
element.maxChildren = maxChildren;
parent.childList.add(elementName);
element.parentList.add(parentName);
elementMap.put(elementName, element);
}
/** {@collect.stats}
* Adds an existing element to the list of legal children for a
* given parent node type.
*
* @param parentName the name of the element that will be the
* new parent of the element.
* @param elementName the name of the element to be addded as a
* child.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>parentName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
*/
protected void addChildElement(String elementName, String parentName) {
Element parent = getElement(parentName);
Element element = getElement(elementName);
parent.childList.add(elementName);
element.parentList.add(parentName);
}
/** {@collect.stats}
* Removes an element from the format. If no element with the
* given name was present, nothing happens and no exception is
* thrown.
*
* @param elementName the name of the element to be removed.
*/
protected void removeElement(String elementName) {
Element element = getElement(elementName, false);
if (element != null) {
Iterator iter = element.parentList.iterator();
while (iter.hasNext()) {
String parentName = (String)iter.next();
Element parent = getElement(parentName, false);
if (parent != null) {
parent.childList.remove(elementName);
}
}
elementMap.remove(elementName);
}
}
/** {@collect.stats}
* Adds a new attribute to a previously defined element that may
* be set to an arbitrary value.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being added.
* @param dataType the data type (string format) of the attribute,
* one of the <code>DATATYPE_*</code> constants.
* @param required <code>true</code> if the attribute must be present.
* @param defaultValue the default value for the attribute, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the predefined constants.
*/
protected void addAttribute(String elementName,
String attrName,
int dataType,
boolean required,
String defaultValue) {
Element element = getElement(elementName);
if (attrName == null) {
throw new IllegalArgumentException("attrName == null!");
}
if (dataType < DATATYPE_STRING || dataType > DATATYPE_DOUBLE) {
throw new IllegalArgumentException("Invalid value for dataType!");
}
Attribute attr = new Attribute();
attr.attrName = attrName;
attr.valueType = VALUE_ARBITRARY;
attr.dataType = dataType;
attr.required = required;
attr.defaultValue = defaultValue;
element.attrList.add(attrName);
element.attrMap.put(attrName, attr);
}
/** {@collect.stats}
* Adds a new attribute to a previously defined element that will
* be defined by a set of enumerated values.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being added.
* @param dataType the data type (string format) of the attribute,
* one of the <code>DATATYPE_*</code> constants.
* @param required <code>true</code> if the attribute must be present.
* @param defaultValue the default value for the attribute, or
* <code>null</code>.
* @param enumeratedValues a <code>List</code> of
* <code>String</code>s containing the legal values for the
* attribute.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the predefined constants.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> is <code>null</code>.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> does not contain at least one
* entry.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> contains an element that is not a
* <code>String</code> or is <code>null</code>.
*/
protected void addAttribute(String elementName,
String attrName,
int dataType,
boolean required,
String defaultValue,
List<String> enumeratedValues) {
Element element = getElement(elementName);
if (attrName == null) {
throw new IllegalArgumentException("attrName == null!");
}
if (dataType < DATATYPE_STRING || dataType > DATATYPE_DOUBLE) {
throw new IllegalArgumentException("Invalid value for dataType!");
}
if (enumeratedValues == null) {
throw new IllegalArgumentException("enumeratedValues == null!");
}
if (enumeratedValues.size() == 0) {
throw new IllegalArgumentException("enumeratedValues is empty!");
}
Iterator iter = enumeratedValues.iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (o == null) {
throw new IllegalArgumentException
("enumeratedValues contains a null!");
}
if (!(o instanceof String)) {
throw new IllegalArgumentException
("enumeratedValues contains a non-String value!");
}
}
Attribute attr = new Attribute();
attr.attrName = attrName;
attr.valueType = VALUE_ENUMERATION;
attr.dataType = dataType;
attr.required = required;
attr.defaultValue = defaultValue;
attr.enumeratedValues = enumeratedValues;
element.attrList.add(attrName);
element.attrMap.put(attrName, attr);
}
/** {@collect.stats}
* Adds a new attribute to a previously defined element that will
* be defined by a range of values.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being added.
* @param dataType the data type (string format) of the attribute,
* one of the <code>DATATYPE_*</code> constants.
* @param required <code>true</code> if the attribute must be present.
* @param defaultValue the default value for the attribute, or
* <code>null</code>.
* @param minValue the smallest (inclusive or exclusive depending
* on the value of <code>minInclusive</code>) legal value for the
* attribute, as a <code>String</code>.
* @param maxValue the largest (inclusive or exclusive depending
* on the value of <code>minInclusive</code>) legal value for the
* attribute, as a <code>String</code>.
* @param minInclusive <code>true</code> if <code>minValue</code>
* is inclusive.
* @param maxInclusive <code>true</code> if <code>maxValue</code>
* is inclusive.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the predefined constants.
*/
protected void addAttribute(String elementName,
String attrName,
int dataType,
boolean required,
String defaultValue,
String minValue,
String maxValue,
boolean minInclusive,
boolean maxInclusive) {
Element element = getElement(elementName);
if (attrName == null) {
throw new IllegalArgumentException("attrName == null!");
}
if (dataType < DATATYPE_STRING || dataType > DATATYPE_DOUBLE) {
throw new IllegalArgumentException("Invalid value for dataType!");
}
Attribute attr = new Attribute();
attr.attrName = attrName;
attr.valueType = VALUE_RANGE;
if (minInclusive) {
attr.valueType |= VALUE_RANGE_MIN_INCLUSIVE_MASK;
}
if (maxInclusive) {
attr.valueType |= VALUE_RANGE_MAX_INCLUSIVE_MASK;
}
attr.dataType = dataType;
attr.required = required;
attr.defaultValue = defaultValue;
attr.minValue = minValue;
attr.maxValue = maxValue;
element.attrList.add(attrName);
element.attrMap.put(attrName, attr);
}
/** {@collect.stats}
* Adds a new attribute to a previously defined element that will
* be defined by a list of values.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being added.
* @param dataType the data type (string format) of the attribute,
* one of the <code>DATATYPE_*</code> constants.
* @param required <code>true</code> if the attribute must be present.
* @param listMinLength the smallest legal number of list items.
* @param listMaxLength the largest legal number of list items.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the predefined constants.
* @exception IllegalArgumentException if
* <code>listMinLength</code> is negative or larger than
* <code>listMaxLength</code>.
*/
protected void addAttribute(String elementName,
String attrName,
int dataType,
boolean required,
int listMinLength,
int listMaxLength) {
Element element = getElement(elementName);
if (attrName == null) {
throw new IllegalArgumentException("attrName == null!");
}
if (dataType < DATATYPE_STRING || dataType > DATATYPE_DOUBLE) {
throw new IllegalArgumentException("Invalid value for dataType!");
}
if (listMinLength < 0 || listMinLength > listMaxLength) {
throw new IllegalArgumentException("Invalid list bounds!");
}
Attribute attr = new Attribute();
attr.attrName = attrName;
attr.valueType = VALUE_LIST;
attr.dataType = dataType;
attr.required = required;
attr.listMinLength = listMinLength;
attr.listMaxLength = listMaxLength;
element.attrList.add(attrName);
element.attrMap.put(attrName, attr);
}
/** {@collect.stats}
* Adds a new attribute to a previously defined element that will
* be defined by the enumerated values <code>TRUE</code> and
* <code>FALSE</code>, with a datatype of
* <code>DATATYPE_BOOLEAN</code>.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being added.
* @param hasDefaultValue <code>true</code> if a default value
* should be present.
* @param defaultValue the default value for the attribute as a
* <code>boolean</code>, ignored if <code>hasDefaultValue</code>
* is <code>false</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code>.
*/
protected void addBooleanAttribute(String elementName,
String attrName,
boolean hasDefaultValue,
boolean defaultValue) {
List values = new ArrayList();
values.add("TRUE");
values.add("FALSE");
String dval = null;
if (hasDefaultValue) {
dval = defaultValue ? "TRUE" : "FALSE";
}
addAttribute(elementName,
attrName,
DATATYPE_BOOLEAN,
true,
dval,
values);
}
/** {@collect.stats}
* Removes an attribute from a previously defined element. If no
* attribute with the given name was present in the given element,
* nothing happens and no exception is thrown.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute being removed.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
*/
protected void removeAttribute(String elementName, String attrName) {
Element element = getElement(elementName);
element.attrList.remove(attrName);
element.attrMap.remove(attrName);
}
/** {@collect.stats}
* Allows an <code>Object</code> reference of a given class type
* to be stored in nodes implementing the named element. The
* value of the <code>Object</code> is unconstrained other than by
* its class type.
*
* <p> If an <code>Object</code> reference was previously allowed,
* the previous settings are overwritten.
*
* @param elementName the name of the element.
* @param classType a <code>Class</code> variable indicating the
* legal class type for the object value.
* @param required <code>true</code> if an object value must be present.
* @param defaultValue the default value for the
* <code>Object</code> reference, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
*/
protected <T> void addObjectValue(String elementName,
Class<T> classType,
boolean required,
T defaultValue)
{
Element element = getElement(elementName);
ObjectValue obj = new ObjectValue();
obj.valueType = VALUE_ARBITRARY;
obj.classType = classType;
obj.defaultValue = defaultValue;
element.objectValue = obj;
}
/** {@collect.stats}
* Allows an <code>Object</code> reference of a given class type
* to be stored in nodes implementing the named element. The
* value of the <code>Object</code> must be one of the values
* given by <code>enumeratedValues</code>.
*
* <p> If an <code>Object</code> reference was previously allowed,
* the previous settings are overwritten.
*
* @param elementName the name of the element.
* @param classType a <code>Class</code> variable indicating the
* legal class type for the object value.
* @param required <code>true</code> if an object value must be present.
* @param defaultValue the default value for the
* <code>Object</code> reference, or <code>null</code>.
* @param enumeratedValues a <code>List</code> of
* <code>Object</code>s containing the legal values for the
* object reference.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> is <code>null</code>.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> does not contain at least one
* entry.
* @exception IllegalArgumentException if
* <code>enumeratedValues</code> contains an element that is not
* an instance of the class type denoted by <code>classType</code>
* or is <code>null</code>.
*/
protected <T> void addObjectValue(String elementName,
Class<T> classType,
boolean required,
T defaultValue,
List<? extends T> enumeratedValues)
{
Element element = getElement(elementName);
if (enumeratedValues == null) {
throw new IllegalArgumentException("enumeratedValues == null!");
}
if (enumeratedValues.size() == 0) {
throw new IllegalArgumentException("enumeratedValues is empty!");
}
Iterator iter = enumeratedValues.iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (o == null) {
throw new IllegalArgumentException("enumeratedValues contains a null!");
}
if (!classType.isInstance(o)) {
throw new IllegalArgumentException("enumeratedValues contains a value not of class classType!");
}
}
ObjectValue obj = new ObjectValue();
obj.valueType = VALUE_ENUMERATION;
obj.classType = classType;
obj.defaultValue = defaultValue;
obj.enumeratedValues = enumeratedValues;
element.objectValue = obj;
}
/** {@collect.stats}
* Allows an <code>Object</code> reference of a given class type
* to be stored in nodes implementing the named element. The
* value of the <code>Object</code> must be within the range given
* by <code>minValue</code> and <code>maxValue</code>.
* Furthermore, the class type must implement the
* <code>Comparable</code> interface.
*
* <p> If an <code>Object</code> reference was previously allowed,
* the previous settings are overwritten.
*
* @param elementName the name of the element.
* @param classType a <code>Class</code> variable indicating the
* legal class type for the object value.
* @param defaultValue the default value for the
* @param minValue the smallest (inclusive or exclusive depending
* on the value of <code>minInclusive</code>) legal value for the
* object value, as a <code>String</code>.
* @param maxValue the largest (inclusive or exclusive depending
* on the value of <code>minInclusive</code>) legal value for the
* object value, as a <code>String</code>.
* @param minInclusive <code>true</code> if <code>minValue</code>
* is inclusive.
* @param maxInclusive <code>true</code> if <code>maxValue</code>
* is inclusive.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this
* format.
*/
protected <T extends Object & Comparable<? super T>> void
addObjectValue(String elementName,
Class<T> classType,
T defaultValue,
Comparable<? super T> minValue,
Comparable<? super T> maxValue,
boolean minInclusive,
boolean maxInclusive)
{
Element element = getElement(elementName);
ObjectValue obj = new ObjectValue();
obj.valueType = VALUE_RANGE;
if (minInclusive) {
obj.valueType |= VALUE_RANGE_MIN_INCLUSIVE_MASK;
}
if (maxInclusive) {
obj.valueType |= VALUE_RANGE_MAX_INCLUSIVE_MASK;
}
obj.classType = classType;
obj.defaultValue = defaultValue;
obj.minValue = minValue;
obj.maxValue = maxValue;
element.objectValue = obj;
}
/** {@collect.stats}
* Allows an <code>Object</code> reference of a given class type
* to be stored in nodes implementing the named element. The
* value of the <code>Object</code> must an array of objects of
* class type given by <code>classType</code>, with at least
* <code>arrayMinLength</code> and at most
* <code>arrayMaxLength</code> elements.
*
* <p> If an <code>Object</code> reference was previously allowed,
* the previous settings are overwritten.
*
* @param elementName the name of the element.
* @param classType a <code>Class</code> variable indicating the
* legal class type for the object value.
* @param arrayMinLength the smallest legal length for the array.
* @param arrayMaxLength the largest legal length for the array.
*
* @exception IllegalArgumentException if <code>elementName</code> is
* not a legal element name for this format.
*/
protected void addObjectValue(String elementName,
Class<?> classType,
int arrayMinLength,
int arrayMaxLength) {
Element element = getElement(elementName);
ObjectValue obj = new ObjectValue();
obj.valueType = VALUE_LIST;
obj.classType = classType;
obj.arrayMinLength = arrayMinLength;
obj.arrayMaxLength = arrayMaxLength;
element.objectValue = obj;
}
/** {@collect.stats}
* Disallows an <code>Object</code> reference from being stored in
* nodes implementing the named element.
*
* @param elementName the name of the element.
*
* @exception IllegalArgumentException if <code>elementName</code> is
* not a legal element name for this format.
*/
protected void removeObjectValue(String elementName) {
Element element = getElement(elementName);
element.objectValue = null;
}
// Utility method
// Methods from IIOMetadataFormat
// Root
public String getRootName() {
return rootName;
}
// Multiplicity
public abstract boolean canNodeAppear(String elementName,
ImageTypeSpecifier imageType);
public int getElementMinChildren(String elementName) {
Element element = getElement(elementName);
if (element.childPolicy != CHILD_POLICY_REPEAT) {
throw new IllegalArgumentException("Child policy not CHILD_POLICY_REPEAT!");
}
return element.minChildren;
}
public int getElementMaxChildren(String elementName) {
Element element = getElement(elementName);
if (element.childPolicy != CHILD_POLICY_REPEAT) {
throw new IllegalArgumentException("Child policy not CHILD_POLICY_REPEAT!");
}
return element.maxChildren;
}
private String getResource(String key, Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
/** {@collect.stats}
* If an applet supplies an implementation of IIOMetadataFormat and
* resource bundles, then the resource bundle will need to be
* accessed via the applet class loader. So first try the context
* class loader to locate the resource bundle.
* If that throws MissingResourceException, then try the
* system class loader.
*/
ClassLoader loader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
ResourceBundle bundle = null;
try {
bundle = ResourceBundle.getBundle(resourceBaseName,
locale, loader);
} catch (MissingResourceException mre) {
try {
bundle = ResourceBundle.getBundle(resourceBaseName, locale);
} catch (MissingResourceException mre1) {
return null;
}
}
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return null;
}
}
/** {@collect.stats}
* Returns a <code>String</code> containing a description of the
* named element, or <code>null</code>. The desciption will be
* localized for the supplied <code>Locale</code> if possible.
*
* <p> The default implementation will first locate a
* <code>ResourceBundle</code> using the current resource base
* name set by <code>setResourceBaseName</code> and the supplied
* <code>Locale</code>, using the fallback mechanism described in
* the comments for <code>ResourceBundle.getBundle</code>. If a
* <code>ResourceBundle</code> is found, the element name will be
* used as a key to its <code>getString</code> method, and the
* result returned. If no <code>ResourceBundle</code> is found,
* or no such key is present, <code>null</code> will be returned.
*
* <p> If <code>locale</code> is <code>null</code>, the current
* default <code>Locale</code> returned by <code>Locale.getLocale</code>
* will be used.
*
* @param elementName the name of the element.
* @param locale the <code>Locale</code> for which localization
* will be attempted.
*
* @return the element description.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
*
* @see #setResourceBaseName
*/
public String getElementDescription(String elementName,
Locale locale) {
Element element = getElement(elementName);
return getResource(elementName, locale);
}
// Children
public int getChildPolicy(String elementName) {
Element element = getElement(elementName);
return element.childPolicy;
}
public String[] getChildNames(String elementName) {
Element element = getElement(elementName);
if (element.childPolicy == CHILD_POLICY_EMPTY) {
return null;
}
return (String[])element.childList.toArray(new String[0]);
}
// Attributes
public String[] getAttributeNames(String elementName) {
Element element = getElement(elementName);
List names = element.attrList;
String[] result = new String[names.size()];
return (String[])names.toArray(result);
}
public int getAttributeValueType(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
return attr.valueType;
}
public int getAttributeDataType(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
return attr.dataType;
}
public boolean isAttributeRequired(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
return attr.required;
}
public String getAttributeDefaultValue(String elementName,
String attrName) {
Attribute attr = getAttribute(elementName, attrName);
return attr.defaultValue;
}
public String[] getAttributeEnumerations(String elementName,
String attrName) {
Attribute attr = getAttribute(elementName, attrName);
if (attr.valueType != VALUE_ENUMERATION) {
throw new IllegalArgumentException
("Attribute not an enumeration!");
}
List values = attr.enumeratedValues;
Iterator iter = values.iterator();
String[] result = new String[values.size()];
return (String[])values.toArray(result);
}
public String getAttributeMinValue(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
if (attr.valueType != VALUE_RANGE &&
attr.valueType != VALUE_RANGE_MIN_INCLUSIVE &&
attr.valueType != VALUE_RANGE_MAX_INCLUSIVE &&
attr.valueType != VALUE_RANGE_MIN_MAX_INCLUSIVE) {
throw new IllegalArgumentException("Attribute not a range!");
}
return attr.minValue;
}
public String getAttributeMaxValue(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
if (attr.valueType != VALUE_RANGE &&
attr.valueType != VALUE_RANGE_MIN_INCLUSIVE &&
attr.valueType != VALUE_RANGE_MAX_INCLUSIVE &&
attr.valueType != VALUE_RANGE_MIN_MAX_INCLUSIVE) {
throw new IllegalArgumentException("Attribute not a range!");
}
return attr.maxValue;
}
public int getAttributeListMinLength(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
if (attr.valueType != VALUE_LIST) {
throw new IllegalArgumentException("Attribute not a list!");
}
return attr.listMinLength;
}
public int getAttributeListMaxLength(String elementName, String attrName) {
Attribute attr = getAttribute(elementName, attrName);
if (attr.valueType != VALUE_LIST) {
throw new IllegalArgumentException("Attribute not a list!");
}
return attr.listMaxLength;
}
/** {@collect.stats}
* Returns a <code>String</code> containing a description of the
* named attribute, or <code>null</code>. The desciption will be
* localized for the supplied <code>Locale</code> if possible.
*
* <p> The default implementation will first locate a
* <code>ResourceBundle</code> using the current resource base
* name set by <code>setResourceBaseName</code> and the supplied
* <code>Locale</code>, using the fallback mechanism described in
* the comments for <code>ResourceBundle.getBundle</code>. If a
* <code>ResourceBundle</code> is found, the element name followed
* by a "/" character followed by the attribute name
* (<code>elementName + "/" + attrName</code>) will be used as a
* key to its <code>getString</code> method, and the result
* returned. If no <code>ResourceBundle</code> is found, or no
* such key is present, <code>null</code> will be returned.
*
* <p> If <code>locale</code> is <code>null</code>, the current
* default <code>Locale</code> returned by <code>Locale.getLocale</code>
* will be used.
*
* @param elementName the name of the element.
* @param attrName the name of the attribute.
* @param locale the <code>Locale</code> for which localization
* will be attempted, or <code>null</code>.
*
* @return the attribute description.
*
* @exception IllegalArgumentException if <code>elementName</code>
* is <code>null</code>, or is not a legal element name for this format.
* @exception IllegalArgumentException if <code>attrName</code> is
* <code>null</code> or is not a legal attribute name for this
* element.
*
* @see #setResourceBaseName
*/
public String getAttributeDescription(String elementName,
String attrName,
Locale locale) {
Element element = getElement(elementName);
if (attrName == null) {
throw new IllegalArgumentException("attrName == null!");
}
Attribute attr = (Attribute)element.attrMap.get(attrName);
if (attr == null) {
throw new IllegalArgumentException("No such attribute!");
}
String key = elementName + "/" + attrName;
return getResource(key, locale);
}
private ObjectValue getObjectValue(String elementName) {
Element element = getElement(elementName);
ObjectValue objv = (ObjectValue)element.objectValue;
if (objv == null) {
throw new IllegalArgumentException("No object within element " +
elementName + "!");
}
return objv;
}
public int getObjectValueType(String elementName) {
Element element = getElement(elementName);
ObjectValue objv = (ObjectValue)element.objectValue;
if (objv == null) {
return VALUE_NONE;
}
return objv.valueType;
}
public Class<?> getObjectClass(String elementName) {
ObjectValue objv = getObjectValue(elementName);
return objv.classType;
}
public Object getObjectDefaultValue(String elementName) {
ObjectValue objv = getObjectValue(elementName);
return objv.defaultValue;
}
public Object[] getObjectEnumerations(String elementName) {
ObjectValue objv = getObjectValue(elementName);
if (objv.valueType != VALUE_ENUMERATION) {
throw new IllegalArgumentException("Not an enumeration!");
}
List vlist = objv.enumeratedValues;
Object[] values = new Object[vlist.size()];
return vlist.toArray(values);
}
public Comparable<?> getObjectMinValue(String elementName) {
ObjectValue objv = getObjectValue(elementName);
if ((objv.valueType & VALUE_RANGE) != VALUE_RANGE) {
throw new IllegalArgumentException("Not a range!");
}
return objv.minValue;
}
public Comparable<?> getObjectMaxValue(String elementName) {
ObjectValue objv = getObjectValue(elementName);
if ((objv.valueType & VALUE_RANGE) != VALUE_RANGE) {
throw new IllegalArgumentException("Not a range!");
}
return objv.maxValue;
}
public int getObjectArrayMinLength(String elementName) {
ObjectValue objv = getObjectValue(elementName);
if (objv.valueType != VALUE_LIST) {
throw new IllegalArgumentException("Not a list!");
}
return objv.arrayMinLength;
}
public int getObjectArrayMaxLength(String elementName) {
ObjectValue objv = getObjectValue(elementName);
if (objv.valueType != VALUE_LIST) {
throw new IllegalArgumentException("Not a list!");
}
return objv.arrayMaxLength;
}
// Standard format descriptor
private synchronized static void createStandardFormat() {
if (standardFormat == null) {
standardFormat = new StandardMetadataFormat();
}
}
/** {@collect.stats}
* Returns an <code>IIOMetadataFormat</code> object describing the
* standard, plug-in neutral <code>javax.imageio_1.0</code>
* metadata document format described in the comment of the
* <code>javax.imageio.metadata</code> package.
*
* @return a predefined <code>IIOMetadataFormat</code> instance.
*/
public static IIOMetadataFormat getStandardFormatInstance() {
createStandardFormat();
return standardFormat;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.UserDataHandler;
class IIODOMException extends DOMException {
public IIODOMException(short code, String message) {
super(code, message);
}
}
class IIONamedNodeMap implements NamedNodeMap {
List nodes;
public IIONamedNodeMap(List nodes) {
this.nodes = nodes;
}
public int getLength() {
return nodes.size();
}
public Node getNamedItem(String name) {
Iterator iter = nodes.iterator();
while (iter.hasNext()) {
Node node = (Node)iter.next();
if (name.equals(node.getNodeName())) {
return node;
}
}
return null;
}
public Node item(int index) {
Node node = (Node)nodes.get(index);
return node;
}
public Node removeNamedItem(java.lang.String name) {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"This NamedNodeMap is read-only!");
}
public Node setNamedItem(Node arg) {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"This NamedNodeMap is read-only!");
}
/** {@collect.stats}
* Equivalent to <code>getNamedItem(localName)</code>.
*/
public Node getNamedItemNS(String namespaceURI, String localName) {
return getNamedItem(localName);
}
/** {@collect.stats}
* Equivalent to <code>setNamedItem(arg)</code>.
*/
public Node setNamedItemNS(Node arg) {
return setNamedItem(arg);
}
/** {@collect.stats}
* Equivalent to <code>removeNamedItem(localName)</code>.
*/
public Node removeNamedItemNS(String namespaceURI, String localName) {
return removeNamedItem(localName);
}
}
class IIONodeList implements NodeList {
List nodes;
public IIONodeList(List nodes) {
this.nodes = nodes;
}
public int getLength() {
return nodes.size();
}
public Node item(int index) {
if (index < 0 || index > nodes.size()) {
return null;
}
return (Node)nodes.get(index);
}
}
class IIOAttr extends IIOMetadataNode implements Attr {
boolean specified = true;
Element owner;
String name;
String value;
public IIOAttr(Element owner, String name, String value) {
this.owner = owner;
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getNodeName() {
return name;
}
public short getNodeType() {
return ATTRIBUTE_NODE;
}
public boolean getSpecified() {
return specified;
}
public String getValue() {
return value;
}
public String getNodeValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void setNodeValue(String value) {
this.value = value;
}
public Element getOwnerElement() {
return owner;
}
public void setOwnerElement(Element owner) {
this.owner = owner;
}
// Start of dummy methods for DOM L3. PENDING: Please revisit
public boolean isId( ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public TypeInfo getSchemaTypeInfo() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object setUserData(String key,
Object data,
UserDataHandler handler) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object getUserData ( String key ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object getFeature ( String feature, String version ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isEqualNode( Node node ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isSameNode( Node node ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String lookupNamespaceURI( String prefix ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isDefaultNamespace(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String lookupPrefix(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
String textContent;
public String getTextContent() throws DOMException {
return textContent;
}
public void setTextContent(String textContent) throws DOMException{
this.textContent = textContent; //PENDING
}
public short compareDocumentPosition(Node other)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String getBaseURI() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
// End of dummy methods for DOM L3. PENDING: Please revisit
}
/** {@collect.stats}
* A class representing a node in a meta-data tree, which implements
* the <a
* href="../../../../api/org/w3c/dom/Element.html">
* <code>org.w3c.dom.Element</code></a> interface and additionally allows
* for the storage of non-textual objects via the
* <code>getUserObject</code> and <code>setUserObject</code> methods.
*
* <p> This class is not intended to be used for general XML
* processing. In particular, <code>Element</code> nodes created
* within the Image I/O API are not compatible with those created by
* Sun's standard implementation of the <code>org.w3.dom</code> API.
* In particular, the implementation is tuned for simple uses and may
* not perform well for intensive processing.
*
* <p> Namespaces are ignored in this implementation. The terms "tag
* name" and "node name" are always considered to be synonymous.
*
* @see IIOMetadata#getAsTree
* @see IIOMetadata#setFromTree
* @see IIOMetadata#mergeTree
*
*/
public class IIOMetadataNode implements Element, NodeList {
/** {@collect.stats}
* The name of the node as a <code>String</code>.
*/
private String nodeName = null;
/** {@collect.stats}
* The value of the node as a <code>String</code>. The Image I/O
* API typically does not make use of the node value.
*/
private String nodeValue = null;
/** {@collect.stats}
* The <code>Object</code> value associated with this node.
*/
private Object userObject = null;
/** {@collect.stats}
* The parent node of this node, or <code>null</code> if this node
* forms the root of its own tree.
*/
private IIOMetadataNode parent = null;
/** {@collect.stats}
* The number of child nodes.
*/
private int numChildren = 0;
/** {@collect.stats}
* The first (leftmost) child node of this node, or
* <code>null</code> if this node is a leaf node.
*/
private IIOMetadataNode firstChild = null;
/** {@collect.stats}
* The last (rightmost) child node of this node, or
* <code>null</code> if this node is a leaf node.
*/
private IIOMetadataNode lastChild = null;
/** {@collect.stats}
* The next (right) sibling node of this node, or
* <code>null</code> if this node is its parent's last child node.
*/
private IIOMetadataNode nextSibling = null;
/** {@collect.stats}
* The previous (left) sibling node of this node, or
* <code>null</code> if this node is its parent's first child node.
*/
private IIOMetadataNode previousSibling = null;
/** {@collect.stats}
* A <code>List</code> of <code>IIOAttr</code> nodes representing
* attributes.
*/
private List attributes = new ArrayList();
/** {@collect.stats}
* Constructs an empty <code>IIOMetadataNode</code>.
*/
public IIOMetadataNode() {}
/** {@collect.stats}
* Constructs an <code>IIOMetadataNode</code> with a given node
* name.
*
* @param nodeName the name of the node, as a <code>String</code>.
*/
public IIOMetadataNode(String nodeName) {
this.nodeName = nodeName;
}
/** {@collect.stats}
* Check that the node is either <code>null</code> or an
* <code>IIOMetadataNode</code>.
*/
private void checkNode(Node node) throws DOMException {
if (node == null) {
return;
}
if (!(node instanceof IIOMetadataNode)) {
throw new IIODOMException(DOMException.WRONG_DOCUMENT_ERR,
"Node not an IIOMetadataNode!");
}
}
// Methods from Node
/** {@collect.stats}
* Returns the node name associated with this node.
*
* @return the node name, as a <code>String</code>.
*/
public String getNodeName() {
return nodeName;
}
public String getNodeValue() throws DOMException {
return nodeValue;
}
public void setNodeValue(String nodeValue) throws DOMException {
this.nodeValue = nodeValue;
}
/** {@collect.stats}
* Returns the node type, which is always
* <code>ELEMENT_NODE</code>.
*
* @return the <code>short</code> value <code>ELEMENT_NODE</code>.
*/
public short getNodeType() {
return ELEMENT_NODE;
}
/** {@collect.stats}
* Returns the parent of this node. A <code>null</code> value
* indicates that the node is the root of its own tree. To add a
* node to an existing tree, use one of the
* <code>insertBefore</code>, <code>replaceChild</code>, or
* <code>appendChild</code> methods.
*
* @return the parent, as a <code>Node</code>.
*
* @see #insertBefore
* @see #replaceChild
* @see #appendChild
*/
public Node getParentNode() {
return parent;
}
public NodeList getChildNodes() {
return this;
}
/** {@collect.stats}
* Returns the first child of this node, or <code>null</code> if
* the node has no children.
*
* @return the first child, as a <code>Node</code>, or
* <code>null</code>
*/
public Node getFirstChild() {
return firstChild;
}
/** {@collect.stats}
* Returns the last child of this node, or <code>null</code> if
* the node has no children.
*
* @return the last child, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getLastChild() {
return lastChild;
}
/** {@collect.stats}
* Returns the previous sibling of this node, or <code>null</code>
* if this node has no previous sibling.
*
* @return the previous sibling, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getPreviousSibling() {
return previousSibling;
}
/** {@collect.stats}
* Returns the next sibling of this node, or <code>null</code> if
* the node has no next sibling.
*
* @return the next sibling, as a <code>Node</code>, or
* <code>null</code>.
*/
public Node getNextSibling() {
return nextSibling;
}
public NamedNodeMap getAttributes() {
return new IIONamedNodeMap(attributes);
}
/** {@collect.stats}
* Returns <code>null</code>, since <code>IIOMetadataNode</code>s
* do not belong to any <code>Document</code>.
*
* @return <code>null</code>.
*/
public Document getOwnerDocument() {
return null;
}
/** {@collect.stats}
* Inserts the node <code>newChild</code> before the existing
* child node <code>refChild</code>. If <code>refChild</code> is
* <code>null</code>, insert <code>newChild</code> at the end of
* the list of children.
*
* @param newChild the <code>Node</code> to insert.
* @param refChild the reference <code>Node</code>.
*
* @return the node being inserted.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node insertBefore(Node newChild,
Node refChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
checkNode(refChild);
IIOMetadataNode newChildNode = (IIOMetadataNode)newChild;
IIOMetadataNode refChildNode = (IIOMetadataNode)refChild;
// Siblings, can be null.
IIOMetadataNode previous = null;
IIOMetadataNode next = null;
if (refChild == null) {
previous = this.lastChild;
next = null;
this.lastChild = newChildNode;
} else {
previous = refChildNode.previousSibling;
next = refChildNode;
}
if (previous != null) {
previous.nextSibling = newChildNode;
}
if (next != null) {
next.previousSibling = newChildNode;
}
newChildNode.parent = this;
newChildNode.previousSibling = previous;
newChildNode.nextSibling = next;
// N.B.: O.K. if refChild == null
if (this.firstChild == refChildNode) {
this.firstChild = newChildNode;
}
++numChildren;
return newChildNode;
}
/** {@collect.stats}
* Replaces the child node <code>oldChild</code> with
* <code>newChild</code> in the list of children, and returns the
* <code>oldChild</code> node.
*
* @param newChild the <code>Node</code> to insert.
* @param oldChild the <code>Node</code> to be replaced.
*
* @return the node replaced.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node replaceChild(Node newChild,
Node oldChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
checkNode(oldChild);
IIOMetadataNode newChildNode = (IIOMetadataNode)newChild;
IIOMetadataNode oldChildNode = (IIOMetadataNode)oldChild;
IIOMetadataNode previous = oldChildNode.previousSibling;
IIOMetadataNode next = oldChildNode.nextSibling;
if (previous != null) {
previous.nextSibling = newChildNode;
}
if (next != null) {
next.previousSibling = newChildNode;
}
newChildNode.parent = this;
newChildNode.previousSibling = previous;
newChildNode.nextSibling = next;
if (firstChild == oldChildNode) {
firstChild = newChildNode;
}
if (lastChild == oldChildNode) {
lastChild = newChildNode;
}
oldChildNode.parent = null;
oldChildNode.previousSibling = null;
oldChildNode.nextSibling = null;
return oldChildNode;
}
/** {@collect.stats}
* Removes the child node indicated by <code>oldChild</code> from
* the list of children, and returns it.
*
* @param oldChild the <code>Node</code> to be removed.
*
* @return the node removed.
*
* @exception IllegalArgumentException if <code>oldChild</code> is
* <code>null</code>.
*/
public Node removeChild(Node oldChild) {
if (oldChild == null) {
throw new IllegalArgumentException("oldChild == null!");
}
checkNode(oldChild);
IIOMetadataNode oldChildNode = (IIOMetadataNode)oldChild;
IIOMetadataNode previous = oldChildNode.previousSibling;
IIOMetadataNode next = oldChildNode.nextSibling;
if (previous != null) {
previous.nextSibling = next;
}
if (next != null) {
next.previousSibling = previous;
}
if (this.firstChild == oldChildNode) {
this.firstChild = next;
}
if (this.lastChild == oldChildNode) {
this.lastChild = previous;
}
oldChildNode.parent = null;
oldChildNode.previousSibling = null;
oldChildNode.nextSibling = null;
--numChildren;
return oldChildNode;
}
/** {@collect.stats}
* Adds the node <code>newChild</code> to the end of the list of
* children of this node.
*
* @param newChild the <code>Node</code> to insert.
*
* @return the node added.
*
* @exception IllegalArgumentException if <code>newChild</code> is
* <code>null</code>.
*/
public Node appendChild(Node newChild) {
if (newChild == null) {
throw new IllegalArgumentException("newChild == null!");
}
checkNode(newChild);
// insertBefore will increment numChildren
return insertBefore(newChild, null);
}
/** {@collect.stats}
* Returns <code>true</code> if this node has child nodes.
*
* @return <code>true</code> if this node has children.
*/
public boolean hasChildNodes() {
return numChildren > 0;
}
/** {@collect.stats}
* Returns a duplicate of this node. The duplicate node has no
* parent (<code>getParentNode</code> returns <code>null</code>).
* If a shallow clone is being performed (<code>deep</code> is
* <code>false</code>), the new node will not have any children or
* siblings. If a deep clone is being performed, the new node
* will form the root of a complete cloned subtree.
*
* @param deep if <code>true</code>, recursively clone the subtree
* under the specified node; if <code>false</code>, clone only the
* node itself.
*
* @return the duplicate node.
*/
public Node cloneNode(boolean deep) {
IIOMetadataNode newNode = new IIOMetadataNode(this.nodeName);
newNode.setUserObject(getUserObject());
// Attributes
if (deep) {
for (IIOMetadataNode child = firstChild;
child != null;
child = child.nextSibling) {
newNode.appendChild(child.cloneNode(true));
}
}
return newNode;
}
/** {@collect.stats}
* Does nothing, since <code>IIOMetadataNode</code>s do not
* contain <code>Text</code> children.
*/
public void normalize() {
}
/** {@collect.stats}
* Returns <code>false</code> since DOM features are not
* supported.
*
* @return <code>false</code>.
*
* @param feature a <code>String</code>, which is ignored.
* @param version a <code>String</code>, which is ignored.
*/
public boolean isSupported(String feature, String version) {
return false;
}
/** {@collect.stats}
* Returns <code>null</code>, since namespaces are not supported.
*/
public String getNamespaceURI() throws DOMException {
return null;
}
/** {@collect.stats}
* Returns <code>null</code>, since namespaces are not supported.
*
* @return <code>null</code>.
*
* @see #setPrefix
*/
public String getPrefix() {
return null;
}
/** {@collect.stats}
* Does nothing, since namespaces are not supported.
*
* @param prefix a <code>String</code>, which is ignored.
*
* @see #getPrefix
*/
public void setPrefix(String prefix) {
}
/** {@collect.stats}
* Equivalent to <code>getNodeName</code>.
*
* @return the node name, as a <code>String</code>.
*/
public String getLocalName() {
return nodeName;
}
// Methods from Element
public String getTagName() {
return nodeName;
}
public String getAttribute(String name) {
Attr attr = getAttributeNode(name);
if (attr == null) {
return "";
}
return attr.getValue();
}
/** {@collect.stats}
* Equivalent to <code>getAttribute(localName)</code>.
*
* @see #setAttributeNS
*/
public String getAttributeNS(String namespaceURI, String localName) {
return getAttribute(localName);
}
public void setAttribute(String name, String value) {
// Name must be valid unicode chars
boolean valid = true;
char[] chs = name.toCharArray();
for (int i=0;i<chs.length;i++) {
if (chs[i] >= 0xfffe) {
valid = false;
break;
}
}
if (!valid) {
throw new IIODOMException(DOMException.INVALID_CHARACTER_ERR,
"Attribute name is illegal!");
}
removeAttribute(name, false);
attributes.add(new IIOAttr(this, name, value));
}
/** {@collect.stats}
* Equivalent to <code>setAttribute(qualifiedName, value)</code>.
*
* @see #getAttributeNS
*/
public void setAttributeNS(String namespaceURI,
String qualifiedName, String value) {
setAttribute(qualifiedName, value);
}
public void removeAttribute(String name) {
removeAttribute(name, true);
}
private void removeAttribute(String name, boolean checkPresent) {
int numAttributes = attributes.size();
for (int i = 0; i < numAttributes; i++) {
IIOAttr attr = (IIOAttr)attributes.get(i);
if (name.equals(attr.getName())) {
attr.setOwnerElement(null);
attributes.remove(i);
return;
}
}
// If we get here, the attribute doesn't exist
if (checkPresent) {
throw new IIODOMException(DOMException.NOT_FOUND_ERR,
"No such attribute!");
}
}
/** {@collect.stats}
* Equivalent to <code>removeAttribute(localName)</code>.
*/
public void removeAttributeNS(String namespaceURI,
String localName) {
removeAttribute(localName);
}
public Attr getAttributeNode(String name) {
Node node = getAttributes().getNamedItem(name);
return (Attr)node;
}
/** {@collect.stats}
* Equivalent to <code>getAttributeNode(localName)</code>.
*
* @see #setAttributeNodeNS
*/
public Attr getAttributeNodeNS(String namespaceURI,
String localName) {
return getAttributeNode(localName);
}
public Attr setAttributeNode(Attr newAttr) throws DOMException {
Element owner = newAttr.getOwnerElement();
if (owner != null) {
if (owner == this) {
return null;
} else {
throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR,
"Attribute is already in use");
}
}
IIOAttr attr;
if (newAttr instanceof IIOAttr) {
attr = (IIOAttr)newAttr;
attr.setOwnerElement(this);
} else {
attr = new IIOAttr(this,
newAttr.getName(),
newAttr.getValue());
}
Attr oldAttr = getAttributeNode(attr.getName());
if (oldAttr != null) {
removeAttributeNode(oldAttr);
}
attributes.add(attr);
return oldAttr;
}
/** {@collect.stats}
* Equivalent to <code>setAttributeNode(newAttr)</code>.
*
* @see #getAttributeNodeNS
*/
public Attr setAttributeNodeNS(Attr newAttr) {
return setAttributeNode(newAttr);
}
public Attr removeAttributeNode(Attr oldAttr) {
removeAttribute(oldAttr.getName());
return oldAttr;
}
public NodeList getElementsByTagName(String name) {
List l = new ArrayList();
getElementsByTagName(name, l);
return new IIONodeList(l);
}
private void getElementsByTagName(String name, List l) {
if (nodeName.equals(name)) {
l.add(this);
}
Node child = getFirstChild();
while (child != null) {
((IIOMetadataNode)child).getElementsByTagName(name, l);
child = child.getNextSibling();
}
}
/** {@collect.stats}
* Equivalent to <code>getElementsByTagName(localName)</code>.
*/
public NodeList getElementsByTagNameNS(String namespaceURI,
String localName) {
return getElementsByTagName(localName);
}
public boolean hasAttributes() {
return attributes.size() > 0;
}
public boolean hasAttribute(String name) {
return getAttributeNode(name) != null;
}
/** {@collect.stats}
* Equivalent to <code>hasAttribute(localName)</code>.
*/
public boolean hasAttributeNS(String namespaceURI,
String localName) {
return hasAttribute(localName);
}
// Methods from NodeList
public int getLength() {
return numChildren;
}
public Node item(int index) {
if (index < 0) {
return null;
}
Node child = getFirstChild();
while (child != null && index-- > 0) {
child = child.getNextSibling();
}
return child;
}
/** {@collect.stats}
* Returns the <code>Object</code> value associated with this node.
*
* @return the user <code>Object</code>.
*
* @see #setUserObject
*/
public Object getUserObject() {
return userObject;
}
/** {@collect.stats}
* Sets the value associated with this node.
*
* @param userObject the user <code>Object</code>.
*
* @see #getUserObject
*/
public void setUserObject(Object userObject) {
this.userObject = userObject;
}
// Start of dummy methods for DOM L3. PENDING: Please revisit
public void setIdAttribute(String name,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public void setIdAttributeNS(String namespaceURI,
String localName,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public void setIdAttributeNode(Attr idAttr,
boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public TypeInfo getSchemaTypeInfo() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object setUserData(String key,
Object data,
UserDataHandler handler) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object getUserData ( String key ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public Object getFeature ( String feature, String version ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isSameNode( Node node ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isEqualNode( Node node ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String lookupNamespaceURI( String prefix ) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public boolean isDefaultNamespace(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String lookupPrefix(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
String textContent;
public String getTextContent() throws DOMException {
return textContent;
}
public void setTextContent(String textContent) throws DOMException{
this.textContent = textContent; //PENDING
}
public short compareDocumentPosition(Node other)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
public String getBaseURI() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported");
}
//End of dummy methods for DOM L3. Please revisit
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
/** {@collect.stats}
* An interface to be implemented by objects that can determine the
* settings of an <code>IIOMetadata</code> object, either by putting
* up a GUI to obtain values from a user, or by other means. This
* interface merely specifies a generic <code>activate</code> method
* that invokes the controller, without regard for how the controller
* obtains values (<i>i.e.</i>, whether the controller puts up a GUI
* or merely computes a set of values is irrelevant to this
* interface).
*
* <p> Within the <code>activate</code> method, a controller obtains
* initial values by querying the <code>IIOMetadata</code> object's
* settings, either using the XML DOM tree or a plug-in specific
* interface, modifies values by whatever means, then modifies the
* <code>IIOMetadata</code> object's settings, using either the
* <code>setFromTree</code> or <code>mergeTree</code> methods, or a
* plug-in specific interface. In general, applications may expect
* that when the <code>activate</code> method returns
* <code>true</code>, the <code>IIOMetadata</code> object is ready for
* use in a write operation.
*
* <p> Vendors may choose to provide GUIs for the
* <code>IIOMetadata</code> subclasses they define for a particular
* plug-in. These can be set up as default controllers in the
* corresponding <code>IIOMetadata</code> subclasses.
*
* <p> Alternatively, an algorithmic process such as a database lookup
* or the parsing of a command line could be used as a controller, in
* which case the <code>activate</code> method would simply look up or
* compute the settings, call methods on <code>IIOMetadata</code> to
* set its state, and return <code>true</code>.
*
* @see IIOMetadata#setController
* @see IIOMetadata#getController
* @see IIOMetadata#getDefaultController
* @see IIOMetadata#hasController
* @see IIOMetadata#activateController
*
*/
public interface IIOMetadataController {
/** {@collect.stats}
* Activates the controller. If <code>true</code> is returned,
* all settings in the <code>IIOMetadata</code> object should be
* ready for use in a write operation. If <code>false</code> is
* returned, no settings in the <code>IIOMetadata</code> object
* will be disturbed (<i>i.e.</i>, the user canceled the
* operation).
*
* @param metadata the <code>IIOMetadata</code> object to be modified.
*
* @return <code>true</code> if the <code>IIOMetadata</code> has been
* modified, <code>false</code> otherwise.
*
* @exception IllegalArgumentException if <code>metadata</code> is
* <code>null</code> or is not an instance of the correct class.
*/
boolean activate(IIOMetadata metadata);
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.metadata;
import org.w3c.dom.Node;
import java.lang.reflect.Method;
/** {@collect.stats}
* An abstract class to be extended by objects that represent metadata
* (non-image data) associated with images and streams. Plug-ins
* represent metadata using opaque, plug-in specific objects. These
* objects, however, provide the ability to access their internal
* information as a tree of <code>IIOMetadataNode</code> objects that
* support the XML DOM interfaces as well as additional interfaces for
* storing non-textual data and retrieving information about legal
* data values. The format of such trees is plug-in dependent, but
* plug-ins may choose to support a plug-in neutral format described
* below. A single plug-in may support multiple metadata formats,
* whose names maybe determined by calling
* <code>getMetadataFormatNames</code>. The plug-in may also support
* a single special format, referred to as the "native" format, which
* is designed to encode its metadata losslessly. This format will
* typically be designed specifically to work with a specific file
* format, so that images may be loaded and saved in the same format
* with no loss of metadata, but may be less useful for transfering
* metadata between an <code>ImageReader</code> and an
* <code>ImageWriter</code> for different image formats. To convert
* between two native formats as losslessly as the image file formats
* will allow, an <code>ImageTranscoder</code> object must be used.
*
* @see javax.imageio.ImageReader#getImageMetadata
* @see javax.imageio.ImageReader#getStreamMetadata
* @see javax.imageio.ImageReader#readAll
* @see javax.imageio.ImageWriter#getDefaultStreamMetadata
* @see javax.imageio.ImageWriter#getDefaultImageMetadata
* @see javax.imageio.ImageWriter#write
* @see javax.imageio.ImageWriter#convertImageMetadata
* @see javax.imageio.ImageWriter#convertStreamMetadata
* @see javax.imageio.IIOImage
* @see javax.imageio.ImageTranscoder
*
*/
public abstract class IIOMetadata {
/** {@collect.stats}
* A boolean indicating whether the concrete subclass supports the
* standard metadata format, set via the constructor.
*/
protected boolean standardFormatSupported;
/** {@collect.stats}
* The name of the native metadata format for this object,
* initialized to <code>null</code> and set via the constructor.
*/
protected String nativeMetadataFormatName = null;
/** {@collect.stats}
* The name of the class implementing <code>IIOMetadataFormat</code>
* and representing the native metadata format, initialized to
* <code>null</code> and set via the constructor.
*/
protected String nativeMetadataFormatClassName = null;
/** {@collect.stats}
* An array of names of formats, other than the standard and
* native formats, that are supported by this plug-in,
* initialized to <code>null</code> and set via the constructor.
*/
protected String[] extraMetadataFormatNames = null;
/** {@collect.stats}
* An array of names of classes implementing <code>IIOMetadataFormat</code>
* and representing the metadata formats, other than the standard and
* native formats, that are supported by this plug-in,
* initialized to <code>null</code> and set via the constructor.
*/
protected String[] extraMetadataFormatClassNames = null;
/** {@collect.stats}
* An <code>IIOMetadataController</code> that is suggested for use
* as the controller for this <code>IIOMetadata</code> object. It
* may be retrieved via <code>getDefaultController</code>. To
* install the default controller, call
* <code>setController(getDefaultController())</code>. This
* instance variable should be set by subclasses that choose to
* provide their own default controller, usually a GUI, for
* setting parameters.
*
* @see IIOMetadataController
* @see #getDefaultController
*/
protected IIOMetadataController defaultController = null;
/** {@collect.stats}
* The <code>IIOMetadataController</code> that will be
* used to provide settings for this <code>IIOMetadata</code>
* object when the <code>activateController</code> method
* is called. This value overrides any default controller,
* even when <code>null</code>.
*
* @see IIOMetadataController
* @see #setController(IIOMetadataController)
* @see #hasController()
* @see #activateController()
*/
protected IIOMetadataController controller = null;
/** {@collect.stats}
* Constructs an empty <code>IIOMetadata</code> object. The
* subclass is responsible for suppying values for all protected
* instance variables that will allow any non-overridden default
* implemtations of methods to satisfy their contracts. For example,
* <code>extraMetadataFormatNames</code> should not have length 0.
*/
protected IIOMetadata() {}
/** {@collect.stats}
* Constructs an <code>IIOMetadata</code> object with the given
* format names and format class names, as well as a boolean
* indicating whether the standard format is supported.
*
* <p> This constructor does not attempt to check the class names
* for validity. Invalid class names may cause exceptions in
* subsequent calls to <code>getMetadataFormat</code>.
*
* @param standardMetadataFormatSupported <code>true</code> if
* this object can return or accept a DOM tree using the standard
* metadata format.
* @param nativeMetadataFormatName the name of the native metadata
* format, as a <code>String</code>, or <code>null</code> if there
* is no native format.
* @param nativeMetadataFormatClassName the name of the class of
* the native metadata format, or <code>null</code> if there is
* no native format.
* @param extraMetadataFormatNames an array of <code>String</code>s
* indicating additional formats supported by this object, or
* <code>null</code> if there are none.
* @param extraMetadataFormatClassNames an array of <code>String</code>s
* indicating the class names of any additional formats supported by
* this object, or <code>null</code> if there are none.
*
* @exception IllegalArgumentException if
* <code>extraMetadataFormatNames</code> has length 0.
* @exception IllegalArgumentException if
* <code>extraMetadataFormatNames</code> and
* <code>extraMetadataFormatClassNames</code> are neither both
* <code>null</code>, nor of the same length.
*/
protected IIOMetadata(boolean standardMetadataFormatSupported,
String nativeMetadataFormatName,
String nativeMetadataFormatClassName,
String[] extraMetadataFormatNames,
String[] extraMetadataFormatClassNames) {
this.standardFormatSupported = standardMetadataFormatSupported;
this.nativeMetadataFormatName = nativeMetadataFormatName;
this.nativeMetadataFormatClassName = nativeMetadataFormatClassName;
if (extraMetadataFormatNames != null) {
if (extraMetadataFormatNames.length == 0) {
throw new IllegalArgumentException
("extraMetadataFormatNames.length == 0!");
}
if (extraMetadataFormatClassNames == null) {
throw new IllegalArgumentException
("extraMetadataFormatNames != null && extraMetadataFormatClassNames == null!");
}
if (extraMetadataFormatClassNames.length !=
extraMetadataFormatNames.length) {
throw new IllegalArgumentException
("extraMetadataFormatClassNames.length != extraMetadataFormatNames.length!");
}
this.extraMetadataFormatNames =
(String[]) extraMetadataFormatNames.clone();
this.extraMetadataFormatClassNames =
(String[]) extraMetadataFormatClassNames.clone();
} else {
if (extraMetadataFormatClassNames != null) {
throw new IllegalArgumentException
("extraMetadataFormatNames == null && extraMetadataFormatClassNames != null!");
}
}
}
/** {@collect.stats}
* Returns <code>true</code> if the standard metadata format is
* supported by <code>getMetadataFormat</code>,
* <code>getAsTree</code>, <code>setFromTree</code>, and
* <code>mergeTree</code>.
*
* <p> The default implementation returns the value of the
* <code>standardFormatSupported</code> instance variable.
*
* @return <code>true</code> if the standard metadata format
* is supported.
*
* @see #getAsTree
* @see #setFromTree
* @see #mergeTree
* @see #getMetadataFormat
*/
public boolean isStandardMetadataFormatSupported() {
return standardFormatSupported;
}
/** {@collect.stats}
* Returns <code>true</code> if this object does not support the
* <code>mergeTree</code>, <code>setFromTree</code>, and
* <code>reset</code> methods.
*
* @return true if this <code>IIOMetadata</code> object cannot be
* modified.
*/
public abstract boolean isReadOnly();
/** {@collect.stats}
* Returns the name of the "native" metadata format for this
* plug-in, which typically allows for lossless encoding and
* transmission of the metadata stored in the format handled by
* this plug-in. If no such format is supported,
* <code>null</code>will be returned.
*
* <p> The structure and contents of the "native" metadata format
* are defined by the plug-in that created this
* <code>IIOMetadata</code> object. Plug-ins for simple formats
* will usually create a dummy node for the root, and then a
* series of child nodes representing individual tags, chunks, or
* keyword/value pairs. A plug-in may choose whether or not to
* document its native format.
*
* <p> The default implementation returns the value of the
* <code>nativeMetadataFormatName</code> instance variable.
*
* @return the name of the native format, or <code>null</code>.
*
* @see #getExtraMetadataFormatNames
* @see #getMetadataFormatNames
*/
public String getNativeMetadataFormatName() {
return nativeMetadataFormatName;
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the names
* of additional metadata formats, other than the native and standard
* formats, recognized by this plug-in's
* <code>getAsTree</code>, <code>setFromTree</code>, and
* <code>mergeTree</code> methods. If there are no such additional
* formats, <code>null</code> is returned.
*
* <p> The default implementation returns a clone of the
* <code>extraMetadataFormatNames</code> instance variable.
*
* @return an array of <code>String</code>s with length at least
* 1, or <code>null</code>.
*
* @see #getAsTree
* @see #setFromTree
* @see #mergeTree
* @see #getNativeMetadataFormatName
* @see #getMetadataFormatNames
*/
public String[] getExtraMetadataFormatNames() {
if (extraMetadataFormatNames == null) {
return null;
}
return (String[])extraMetadataFormatNames.clone();
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the names
* of all metadata formats, including the native and standard
* formats, recognized by this plug-in's <code>getAsTree</code>,
* <code>setFromTree</code>, and <code>mergeTree</code> methods.
* If there are no such formats, <code>null</code> is returned.
*
* <p> The default implementation calls
* <code>getNativeMetadataFormatName</code>,
* <code>isStandardMetadataFormatSupported</code>, and
* <code>getExtraMetadataFormatNames</code> and returns the
* combined results.
*
* @return an array of <code>String</code>s.
*
* @see #getNativeMetadataFormatName
* @see #isStandardMetadataFormatSupported
* @see #getExtraMetadataFormatNames
*/
public String[] getMetadataFormatNames() {
String nativeName = getNativeMetadataFormatName();
String standardName = isStandardMetadataFormatSupported() ?
IIOMetadataFormatImpl.standardMetadataFormatName : null;
String[] extraNames = getExtraMetadataFormatNames();
int numFormats = 0;
if (nativeName != null) {
++numFormats;
}
if (standardName != null) {
++numFormats;
}
if (extraNames != null) {
numFormats += extraNames.length;
}
if (numFormats == 0) {
return null;
}
String[] formats = new String[numFormats];
int index = 0;
if (nativeName != null) {
formats[index++] = nativeName;
}
if (standardName != null) {
formats[index++] = standardName;
}
if (extraNames != null) {
for (int i = 0; i < extraNames.length; i++) {
formats[index++] = extraNames[i];
}
}
return formats;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataFormat</code> object describing the
* given metadata format, or <code>null</code> if no description
* is available. The supplied name must be one of those returned
* by <code>getMetadataFormatNames</code> (<i>i.e.</i>, either the
* native format name, the standard format name, or one of those
* returned by <code>getExtraMetadataFormatNames</code>).
*
* <p> The default implementation checks the name against the
* global standard metadata format name, and returns that format
* if it is supported. Otherwise, it checks against the native
* format names followed by any additional format names. If a
* match is found, it retrieves the name of the
* <code>IIOMetadataFormat</code> class from
* <code>nativeMetadataFormatClassName</code> or
* <code>extraMetadataFormatClassNames</code> as appropriate, and
* constructs an instance of that class using its
* <code>getInstance</code> method.
*
* @param formatName the desired metadata format.
*
* @return an <code>IIOMetadataFormat</code> object.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not one of the names recognized by
* the plug-in.
* @exception IllegalStateException if the class corresponding to
* the format name cannot be loaded.
*/
public IIOMetadataFormat getMetadataFormat(String formatName) {
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
if (standardFormatSupported
&& formatName.equals
(IIOMetadataFormatImpl.standardMetadataFormatName)) {
return IIOMetadataFormatImpl.getStandardFormatInstance();
}
String formatClassName = null;
if (formatName.equals(nativeMetadataFormatName)) {
formatClassName = nativeMetadataFormatClassName;
} else if (extraMetadataFormatNames != null) {
for (int i = 0; i < extraMetadataFormatNames.length; i++) {
if (formatName.equals(extraMetadataFormatNames[i])) {
formatClassName = extraMetadataFormatClassNames[i];
break; // out of for
}
}
}
if (formatClassName == null) {
throw new IllegalArgumentException("Unsupported format name");
}
try {
Class cls = null;
final Object o = this;
// firstly we try to use classloader used for loading
// the IIOMetadata implemantation for this plugin.
ClassLoader loader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return o.getClass().getClassLoader();
}
});
try {
cls = Class.forName(formatClassName, true,
loader);
} catch (ClassNotFoundException e) {
// we failed to load IIOMetadataFormat class by
// using IIOMetadata classloader.Next try is to
// use thread context classloader.
loader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
try {
cls = Class.forName(formatClassName, true,
loader);
} catch (ClassNotFoundException e1) {
// finally we try to use system classloader in case
// if we failed to load IIOMetadataFormat implementation
// class above.
cls = Class.forName(formatClassName, true,
ClassLoader.getSystemClassLoader());
}
}
Method meth = cls.getMethod("getInstance");
return (IIOMetadataFormat) meth.invoke(null);
} catch (Exception e) {
RuntimeException ex =
new IllegalStateException ("Can't obtain format");
ex.initCause(e);
throw ex;
}
}
/** {@collect.stats}
* Returns an XML DOM <code>Node</code> object that represents the
* root of a tree of metadata contained within this object
* according to the conventions defined by a given metadata
* format.
*
* <p> The names of the available metadata formats may be queried
* using the <code>getMetadataFormatNames</code> method.
*
* @param formatName the desired metadata format.
*
* @return an XML DOM <code>Node</code> object forming the
* root of a tree.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not one of the names returned by
* <code>getMetadataFormatNames</code>.
*
* @see #getMetadataFormatNames
* @see #setFromTree
* @see #mergeTree
*/
public abstract Node getAsTree(String formatName);
/** {@collect.stats}
* Alters the internal state of this <code>IIOMetadata</code>
* object from a tree of XML DOM <code>Node</code>s whose syntax
* is defined by the given metadata format. The previous state is
* altered only as necessary to accomodate the nodes that are
* present in the given tree. If the tree structure or contents
* are invalid, an <code>IIOInvalidTreeException</code> will be
* thrown.
*
* <p> As the semantics of how a tree or subtree may be merged with
* another tree are completely format-specific, plug-in authors may
* implement this method in whatever manner is most appropriate for
* the format, including simply replacing all existing state with the
* contents of the given tree.
*
* @param formatName the desired metadata format.
* @param root an XML DOM <code>Node</code> object forming the
* root of a tree.
*
* @exception IllegalStateException if this object is read-only.
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not one of the names returned by
* <code>getMetadataFormatNames</code>.
* @exception IllegalArgumentException if <code>root</code> is
* <code>null</code>.
* @exception IIOInvalidTreeException if the tree cannot be parsed
* successfully using the rules of the given format.
*
* @see #getMetadataFormatNames
* @see #getAsTree
* @see #setFromTree
*/
public abstract void mergeTree(String formatName, Node root)
throws IIOInvalidTreeException;
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the chroma
* information of the standard <code>javax_imageio_1.0</code>
* metadata format, or <code>null</code> if no such information is
* available. This method is intended to be called by the utility
* routine <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardChromaNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the
* compression information of the standard
* <code>javax_imageio_1.0</code> metadata format, or
* <code>null</code> if no such information is available. This
* method is intended to be called by the utility routine
* <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardCompressionNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the data
* format information of the standard
* <code>javax_imageio_1.0</code> metadata format, or
* <code>null</code> if no such information is available. This
* method is intended to be called by the utility routine
* <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardDataNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the
* dimension information of the standard
* <code>javax_imageio_1.0</code> metadata format, or
* <code>null</code> if no such information is available. This
* method is intended to be called by the utility routine
* <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardDimensionNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the document
* information of the standard <code>javax_imageio_1.0</code>
* metadata format, or <code>null</code> if no such information is
* available. This method is intended to be called by the utility
* routine <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardDocumentNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the textual
* information of the standard <code>javax_imageio_1.0</code>
* metadata format, or <code>null</code> if no such information is
* available. This method is intended to be called by the utility
* routine <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardTextNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the tiling
* information of the standard <code>javax_imageio_1.0</code>
* metadata format, or <code>null</code> if no such information is
* available. This method is intended to be called by the utility
* routine <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*
* @see #getStandardTree
*/
protected IIOMetadataNode getStandardTileNode() {
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadataNode</code> representing the
* transparency information of the standard
* <code>javax_imageio_1.0</code> metadata format, or
* <code>null</code> if no such information is available. This
* method is intended to be called by the utility routine
* <code>getStandardTree</code>.
*
* <p> The default implementation returns <code>null</code>.
*
* <p> Subclasses should override this method to produce an
* appropriate subtree if they wish to support the standard
* metadata format.
*
* @return an <code>IIOMetadataNode</code>, or <code>null</code>.
*/
protected IIOMetadataNode getStandardTransparencyNode() {
return null;
}
/** {@collect.stats}
* Appends a new node to an existing node, if the new node is
* non-<code>null</code>.
*/
private void append(IIOMetadataNode root, IIOMetadataNode node) {
if (node != null) {
root.appendChild(node);
}
}
/** {@collect.stats}
* A utility method to return a tree of
* <code>IIOMetadataNode</code>s representing the metadata
* contained within this object according to the conventions of
* the standard <code>javax_imageio_1.0</code> metadata format.
*
* <p> This method calls the various <code>getStandard*Node</code>
* methods to supply each of the subtrees rooted at the children
* of the root node. If any of those methods returns
* <code>null</code>, the corresponding subtree will be omitted.
* If all of them return <code>null</code>, a tree consisting of a
* single root node will be returned.
*
* @return an <code>IIOMetadataNode</code> representing the root
* of a metadata tree in the <code>javax_imageio_1.0</code>
* format.
*
* @see #getStandardChromaNode
* @see #getStandardCompressionNode
* @see #getStandardDataNode
* @see #getStandardDimensionNode
* @see #getStandardDocumentNode
* @see #getStandardTextNode
* @see #getStandardTileNode
* @see #getStandardTransparencyNode
*/
protected final IIOMetadataNode getStandardTree() {
IIOMetadataNode root = new IIOMetadataNode
(IIOMetadataFormatImpl.standardMetadataFormatName);
append(root, getStandardChromaNode());
append(root, getStandardCompressionNode());
append(root, getStandardDataNode());
append(root, getStandardDimensionNode());
append(root, getStandardDocumentNode());
append(root, getStandardTextNode());
append(root, getStandardTileNode());
append(root, getStandardTransparencyNode());
return root;
}
/** {@collect.stats}
* Sets the internal state of this <code>IIOMetadata</code> object
* from a tree of XML DOM <code>Node</code>s whose syntax is
* defined by the given metadata format. The previous state is
* discarded. If the tree's structure or contents are invalid, an
* <code>IIOInvalidTreeException</code> will be thrown.
*
* <p> The default implementation calls <code>reset</code>
* followed by <code>mergeTree(formatName, root)</code>.
*
* @param formatName the desired metadata format.
* @param root an XML DOM <code>Node</code> object forming the
* root of a tree.
*
* @exception IllegalStateException if this object is read-only.
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not one of the names returned by
* <code>getMetadataFormatNames</code>.
* @exception IllegalArgumentException if <code>root</code> is
* <code>null</code>.
* @exception IIOInvalidTreeException if the tree cannot be parsed
* successfully using the rules of the given format.
*
* @see #getMetadataFormatNames
* @see #getAsTree
* @see #mergeTree
*/
public void setFromTree(String formatName, Node root)
throws IIOInvalidTreeException {
reset();
mergeTree(formatName, root);
}
/** {@collect.stats}
* Resets all the data stored in this object to default values,
* usually to the state this object was in immediately after
* construction, though the precise semantics are plug-in specific.
* Note that there are many possible default values, depending on
* how the object was created.
*
* @exception IllegalStateException if this object is read-only.
*
* @see javax.imageio.ImageReader#getStreamMetadata
* @see javax.imageio.ImageReader#getImageMetadata
* @see javax.imageio.ImageWriter#getDefaultStreamMetadata
* @see javax.imageio.ImageWriter#getDefaultImageMetadata
*/
public abstract void reset();
/** {@collect.stats}
* Sets the <code>IIOMetadataController</code> to be used
* to provide settings for this <code>IIOMetadata</code>
* object when the <code>activateController</code> method
* is called, overriding any default controller. If the
* argument is <code>null</code>, no controller will be
* used, including any default. To restore the default, use
* <code>setController(getDefaultController())</code>.
*
* <p> The default implementation sets the <code>controller</code>
* instance variable to the supplied value.
*
* @param controller An appropriate
* <code>IIOMetadataController</code>, or <code>null</code>.
*
* @see IIOMetadataController
* @see #getController
* @see #getDefaultController
* @see #hasController
* @see #activateController()
*/
public void setController(IIOMetadataController controller) {
this.controller = controller;
}
/** {@collect.stats}
* Returns whatever <code>IIOMetadataController</code> is currently
* installed. This could be the default if there is one,
* <code>null</code>, or the argument of the most recent call
* to <code>setController</code>.
*
* <p> The default implementation returns the value of the
* <code>controller</code> instance variable.
*
* @return the currently installed
* <code>IIOMetadataController</code>, or <code>null</code>.
*
* @see IIOMetadataController
* @see #setController
* @see #getDefaultController
* @see #hasController
* @see #activateController()
*/
public IIOMetadataController getController() {
return controller;
}
/** {@collect.stats}
* Returns the default <code>IIOMetadataController</code>, if there
* is one, regardless of the currently installed controller. If
* there is no default controller, returns <code>null</code>.
*
* <p> The default implementation returns the value of the
* <code>defaultController</code> instance variable.
*
* @return the default <code>IIOMetadataController</code>, or
* <code>null</code>.
*
* @see IIOMetadataController
* @see #setController(IIOMetadataController)
* @see #getController
* @see #hasController
* @see #activateController()
*/
public IIOMetadataController getDefaultController() {
return defaultController;
}
/** {@collect.stats}
* Returns <code>true</code> if there is a controller installed
* for this <code>IIOMetadata</code> object.
*
* <p> The default implementation returns <code>true</code> if the
* <code>getController</code> method returns a
* non-<code>null</code> value.
*
* @return <code>true</code> if a controller is installed.
*
* @see IIOMetadataController
* @see #setController(IIOMetadataController)
* @see #getController
* @see #getDefaultController
* @see #activateController()
*/
public boolean hasController() {
return (getController() != null);
}
/** {@collect.stats}
* Activates the installed <code>IIOMetadataController</code> for
* this <code>IIOMetadata</code> object and returns the resulting
* value. When this method returns <code>true</code>, all values for this
* <code>IIOMetadata</code> object will be ready for the next write
* operation. If <code>false</code> is
* returned, no settings in this object will have been disturbed
* (<i>i.e.</i>, the user canceled the operation).
*
* <p> Ordinarily, the controller will be a GUI providing a user
* interface for a subclass of <code>IIOMetadata</code> for a
* particular plug-in. Controllers need not be GUIs, however.
*
* <p> The default implementation calls <code>getController</code>
* and the calls <code>activate</code> on the returned object if
* <code>hasController</code> returns <code>true</code>.
*
* @return <code>true</code> if the controller completed normally.
*
* @exception IllegalStateException if there is no controller
* currently installed.
*
* @see IIOMetadataController
* @see #setController(IIOMetadataController)
* @see #getController
* @see #getDefaultController
* @see #hasController
*/
public boolean activateController() {
if (!hasController()) {
throw new IllegalStateException("hasController() == false!");
}
return getController().activate(this);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Dimension;
import java.util.Locale;
/** {@collect.stats}
* A class describing how a stream is to be encoded. Instances of
* this class or its subclasses are used to supply prescriptive
* "how-to" information to instances of <code>ImageWriter</code>.
*
* <p> A plug-in for a specific image format may define a subclass of
* this class, and return objects of that class from the
* <code>getDefaultWriteParam</code> method of its
* <code>ImageWriter</code> implementation. For example, the built-in
* JPEG writer plug-in will return instances of
* <code>javax.imageio.plugins.jpeg.JPEGImageWriteParam</code>.
*
* <p> The region of the image to be written is determined by first
* intersecting the actual bounds of the image with the rectangle
* specified by <code>IIOParam.setSourceRegion</code>, if any. If the
* resulting rectangle has a width or height of zero, the writer will
* throw an <code>IIOException</code>. If the intersection is
* non-empty, writing will commence with the first subsampled pixel
* and include additional pixels within the intersected bounds
* according to the horizontal and vertical subsampling factors
* specified by {@link IIOParam#setSourceSubsampling
* <code>IIOParam.setSourceSubsampling</code>}.
*
* <p> Individual features such as tiling, progressive encoding, and
* compression may be set in one of four modes.
* <code>MODE_DISABLED</code> disables the features;
* <code>MODE_DEFAULT</code> enables the feature with
* writer-controlled parameter values; <code>MODE_EXPLICIT</code>
* enables the feature and allows the use of a <code>set</code> method
* to provide additional parameters; and
* <code>MODE_COPY_FROM_METADATA</code> copies relevant parameter
* values from the stream and image metadata objects passed to the
* writer. The default for all features is
* <code>MODE_COPY_FROM_METADATA</code>. Non-standard features
* supplied in subclasses are encouraged, but not required to use a
* similar scheme.
*
* <p> Plug-in writers may extend the functionality of
* <code>ImageWriteParam</code> by providing a subclass that implements
* additional, plug-in specific interfaces. It is up to the plug-in
* to document what interfaces are available and how they are to be
* used. Writers will silently ignore any extended features of an
* <code>ImageWriteParam</code> subclass of which they are not aware.
* Also, they may ignore any optional features that they normally
* disable when creating their own <code>ImageWriteParam</code>
* instances via <code>getDefaultWriteParam</code>.
*
* <p> Note that unless a query method exists for a capability, it must
* be supported by all <code>ImageWriter</code> implementations
* (<i>e.g.</i> progressive encoding is optional, but subsampling must be
* supported).
*
*
* @see ImageReadParam
*/
public class ImageWriteParam extends IIOParam {
/** {@collect.stats}
* A constant value that may be passed into methods such as
* <code>setTilingMode</code>, <code>setProgressiveMode</code>,
* and <code>setCompressionMode</code> to disable a feature for
* future writes. That is, when this mode is set the stream will
* <b>not</b> be tiled, progressive, or compressed, and the
* relevant accessor methods will throw an
* <code>IllegalStateException</code>.
*
* @see #MODE_EXPLICIT
* @see #MODE_COPY_FROM_METADATA
* @see #MODE_DEFAULT
* @see #setProgressiveMode
* @see #getProgressiveMode
* @see #setTilingMode
* @see #getTilingMode
* @see #setCompressionMode
* @see #getCompressionMode
*/
public static final int MODE_DISABLED = 0;
/** {@collect.stats}
* A constant value that may be passed into methods such as
* <code>setTilingMode</code>,
* <code>setProgressiveMode</code>, and
* <code>setCompressionMode</code> to enable that feature for
* future writes. That is, when this mode is enabled the stream
* will be tiled, progressive, or compressed according to a
* sensible default chosen internally by the writer in a plug-in
* dependent way, and the relevant accessor methods will
* throw an <code>IllegalStateException</code>.
*
* @see #MODE_DISABLED
* @see #MODE_EXPLICIT
* @see #MODE_COPY_FROM_METADATA
* @see #setProgressiveMode
* @see #getProgressiveMode
* @see #setTilingMode
* @see #getTilingMode
* @see #setCompressionMode
* @see #getCompressionMode
*/
public static final int MODE_DEFAULT = 1;
/** {@collect.stats}
* A constant value that may be passed into methods such as
* <code>setTilingMode</code> or <code>setCompressionMode</code>
* to enable a feature for future writes. That is, when this mode
* is set the stream will be tiled or compressed according to
* additional information supplied to the corresponding
* <code>set</code> methods in this class and retrievable from the
* corresponding <code>get</code> methods. Note that this mode is
* not supported for progressive output.
*
* @see #MODE_DISABLED
* @see #MODE_COPY_FROM_METADATA
* @see #MODE_DEFAULT
* @see #setProgressiveMode
* @see #getProgressiveMode
* @see #setTilingMode
* @see #getTilingMode
* @see #setCompressionMode
* @see #getCompressionMode
*/
public static final int MODE_EXPLICIT = 2;
/** {@collect.stats}
* A constant value that may be passed into methods such as
* <code>setTilingMode</code>, <code>setProgressiveMode</code>, or
* <code>setCompressionMode</code> to enable that feature for
* future writes. That is, when this mode is enabled the stream
* will be tiled, progressive, or compressed based on the contents
* of stream and/or image metadata passed into the write
* operation, and any relevant accessor methods will throw an
* <code>IllegalStateException</code>.
*
* <p> This is the default mode for all features, so that a read
* including metadata followed by a write including metadata will
* preserve as much information as possible.
*
* @see #MODE_DISABLED
* @see #MODE_EXPLICIT
* @see #MODE_DEFAULT
* @see #setProgressiveMode
* @see #getProgressiveMode
* @see #setTilingMode
* @see #getTilingMode
* @see #setCompressionMode
* @see #getCompressionMode
*/
public static final int MODE_COPY_FROM_METADATA = 3;
// If more modes are added, this should be updated.
private static final int MAX_MODE = MODE_COPY_FROM_METADATA;
/** {@collect.stats}
* A <code>boolean</code> that is <code>true</code> if this
* <code>ImageWriteParam</code> allows tile width and tile height
* parameters to be set. By default, the value is
* <code>false</code>. Subclasses must set the value manually.
*
* <p> Subclasses that do not support writing tiles should ensure
* that this value is set to <code>false</code>.
*/
protected boolean canWriteTiles = false;
/** {@collect.stats}
* The mode controlling tiling settings, which Must be
* set to one of the four <code>MODE_*</code> values. The default
* is <code>MODE_COPY_FROM_METADATA</code>.
*
* <p> Subclasses that do not writing tiles may ignore this value.
*
* @see #MODE_DISABLED
* @see #MODE_EXPLICIT
* @see #MODE_COPY_FROM_METADATA
* @see #MODE_DEFAULT
* @see #setTilingMode
* @see #getTilingMode
*/
protected int tilingMode = MODE_COPY_FROM_METADATA;
/** {@collect.stats}
* An array of preferred tile size range pairs. The default value
* is <code>null</code>, which indicates that there are no
* preferred sizes. If the value is non-<code>null</code>, it
* must have an even length of at least two.
*
* <p> Subclasses that do not support writing tiles may ignore
* this value.
*
* @see #getPreferredTileSizes
*/
protected Dimension[] preferredTileSizes = null;
/** {@collect.stats}
* A <code>boolean</code> that is <code>true</code> if tiling
* parameters have been specified.
*
* <p> Subclasses that do not support writing tiles may ignore
* this value.
*/
protected boolean tilingSet = false;
/** {@collect.stats}
* The width of each tile if tiling has been set, or 0 otherwise.
*
* <p> Subclasses that do not support tiling may ignore this
* value.
*/
protected int tileWidth = 0;
/** {@collect.stats}
* The height of each tile if tiling has been set, or 0 otherwise.
* The initial value is <code>0</code>.
*
* <p> Subclasses that do not support tiling may ignore this
* value.
*/
protected int tileHeight = 0;
/** {@collect.stats}
* A <code>boolean</code> that is <code>true</code> if this
* <code>ImageWriteParam</code> allows tiling grid offset
* parameters to be set. By default, the value is
* <code>false</code>. Subclasses must set the value manually.
*
* <p> Subclasses that do not support writing tiles, or that
* supprt writing but not offsetting tiles must ensure that this
* value is set to <code>false</code>.
*/
protected boolean canOffsetTiles = false;
/** {@collect.stats}
* The amount by which the tile grid origin should be offset
* horizontally from the image origin if tiling has been set,
* or 0 otherwise. The initial value is <code>0</code>.
*
* <p> Subclasses that do not support offsetting tiles may ignore
* this value.
*/
protected int tileGridXOffset = 0;
/** {@collect.stats}
* The amount by which the tile grid origin should be offset
* vertically from the image origin if tiling has been set,
* or 0 otherwise. The initial value is <code>0</code>.
*
* <p> Subclasses that do not support offsetting tiles may ignore
* this value.
*/
protected int tileGridYOffset = 0;
/** {@collect.stats}
* A <code>boolean</code> that is <code>true</code> if this
* <code>ImageWriteParam</code> allows images to be written as a
* progressive sequence of increasing quality passes. By default,
* the value is <code>false</code>. Subclasses must set the value
* manually.
*
* <p> Subclasses that do not support progressive encoding must
* ensure that this value is set to <code>false</code>.
*/
protected boolean canWriteProgressive = false;
/** {@collect.stats}
* The mode controlling progressive encoding, which must be set to
* one of the four <code>MODE_*</code> values, except
* <code>MODE_EXPLICIT</code>. The default is
* <code>MODE_COPY_FROM_METADATA</code>.
*
* <p> Subclasses that do not support progressive encoding may
* ignore this value.
*
* @see #MODE_DISABLED
* @see #MODE_EXPLICIT
* @see #MODE_COPY_FROM_METADATA
* @see #MODE_DEFAULT
* @see #setProgressiveMode
* @see #getProgressiveMode
*/
protected int progressiveMode = MODE_COPY_FROM_METADATA;
/** {@collect.stats}
* A <code>boolean</code> that is <code>true</code> if this writer
* can write images using compression. By default, the value is
* <code>false</code>. Subclasses must set the value manually.
*
* <p> Subclasses that do not support compression must ensure that
* this value is set to <code>false</code>.
*/
protected boolean canWriteCompressed = false;
/** {@collect.stats}
* The mode controlling compression settings, which must be set to
* one of the four <code>MODE_*</code> values. The default is
* <code>MODE_COPY_FROM_METADATA</code>.
*
* <p> Subclasses that do not support compression may ignore this
* value.
*
* @see #MODE_DISABLED
* @see #MODE_EXPLICIT
* @see #MODE_COPY_FROM_METADATA
* @see #MODE_DEFAULT
* @see #setCompressionMode
* @see #getCompressionMode
*/
protected int compressionMode = MODE_COPY_FROM_METADATA;
/** {@collect.stats}
* An array of <code>String</code>s containing the names of the
* available compression types. Subclasses must set the value
* manually.
*
* <p> Subclasses that do not support compression may ignore this
* value.
*/
protected String[] compressionTypes = null;
/** {@collect.stats}
* A <code>String</code> containing the name of the current
* compression type, or <code>null</code> if none is set.
*
* <p> Subclasses that do not support compression may ignore this
* value.
*/
protected String compressionType = null;
/** {@collect.stats}
* A <code>float</code> containing the current compression quality
* setting. The initial value is <code>1.0F</code>.
*
* <p> Subclasses that do not support compression may ignore this
* value.
*/
protected float compressionQuality = 1.0F;
/** {@collect.stats}
* A <code>Locale</code> to be used to localize compression type
* names and quality descriptions, or <code>null</code> to use a
* default <code>Locale</code>. Subclasses must set the value
* manually.
*/
protected Locale locale = null;
/** {@collect.stats}
* Constructs an empty <code>ImageWriteParam</code>. It is up to
* the subclass to set up the instance variables properly.
*/
protected ImageWriteParam() {}
/** {@collect.stats}
* Constructs an <code>ImageWriteParam</code> set to use a
* given <code>Locale</code>.
*
* @param locale a <code>Locale</code> to be used to localize
* compression type names and quality descriptions, or
* <code>null</code>.
*/
public ImageWriteParam(Locale locale) {
this.locale = locale;
}
// Return a deep copy of the array
private static Dimension[] clonePreferredTileSizes(Dimension[] sizes) {
if (sizes == null) {
return null;
}
Dimension[] temp = new Dimension[sizes.length];
for (int i = 0; i < sizes.length; i++) {
temp[i] = new Dimension(sizes[i]);
}
return temp;
}
/** {@collect.stats}
* Returns the currently set <code>Locale</code>, or
* <code>null</code> if only a default <code>Locale</code> is
* supported.
*
* @return the current <code>Locale</code>, or <code>null</code>.
*/
public Locale getLocale() {
return locale;
}
/** {@collect.stats}
* Returns <code>true</code> if the writer can perform tiling
* while writing. If this method returns <code>false</code>, then
* <code>setTiling</code> will throw an
* <code>UnsupportedOperationException</code>.
*
* @return <code>true</code> if the writer supports tiling.
*
* @see #canOffsetTiles()
* @see #setTiling(int, int, int, int)
*/
public boolean canWriteTiles() {
return canWriteTiles;
}
/** {@collect.stats}
* Returns <code>true</code> if the writer can perform tiling with
* non-zero grid offsets while writing. If this method returns
* <code>false</code>, then <code>setTiling</code> will throw an
* <code>UnsupportedOperationException</code> if the grid offset
* arguments are not both zero. If <code>canWriteTiles</code>
* returns <code>false</code>, this method will return
* <code>false</code> as well.
*
* @return <code>true</code> if the writer supports non-zero tile
* offsets.
*
* @see #canWriteTiles()
* @see #setTiling(int, int, int, int)
*/
public boolean canOffsetTiles() {
return canOffsetTiles;
}
/** {@collect.stats}
* Determines whether the image will be tiled in the output
* stream and, if it will, how the tiling parameters will be
* determined. The modes are interpreted as follows:
*
* <ul>
*
* <li><code>MODE_DISABLED</code> - The image will not be tiled.
* <code>setTiling</code> will throw an
* <code>IllegalStateException</code>.
*
* <li><code>MODE_DEFAULT</code> - The image will be tiled using
* default parameters. <code>setTiling</code> will throw an
* <code>IllegalStateException</code>.
*
* <li><code>MODE_EXPLICIT</code> - The image will be tiled
* according to parameters given in the {@link #setTiling
* <code>setTiling</code>} method. Any previously set tiling
* parameters are discarded.
*
* <li><code>MODE_COPY_FROM_METADATA</code> - The image will
* conform to the metadata object passed in to a write.
* <code>setTiling</code> will throw an
* <code>IllegalStateException</code>.
*
* </ul>
*
* @param mode The mode to use for tiling.
*
* @exception UnsupportedOperationException if
* <code>canWriteTiles</code> returns <code>false</code>.
* @exception IllegalArgumentException if <code>mode</code> is not
* one of the modes listed above.
*
* @see #setTiling
* @see #getTilingMode
*/
public void setTilingMode(int mode) {
if (canWriteTiles() == false) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (mode < MODE_DISABLED || mode > MAX_MODE) {
throw new IllegalArgumentException("Illegal value for mode!");
}
this.tilingMode = mode;
if (mode == MODE_EXPLICIT) {
unsetTiling();
}
}
/** {@collect.stats}
* Returns the current tiling mode, if tiling is supported.
* Otherwise throws an <code>UnsupportedOperationException</code>.
*
* @return the current tiling mode.
*
* @exception UnsupportedOperationException if
* <code>canWriteTiles</code> returns <code>false</code>.
*
* @see #setTilingMode
*/
public int getTilingMode() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported");
}
return tilingMode;
}
/** {@collect.stats}
* Returns an array of <code>Dimension</code>s indicating the
* legal size ranges for tiles as they will be encoded in the
* output file or stream. The returned array is a copy.
*
* <p> The information is returned as a set of pairs; the first
* element of a pair contains an (inclusive) minimum width and
* height, and the second element contains an (inclusive) maximum
* width and height. Together, each pair defines a valid range of
* sizes. To specify a fixed size, use the same width and height
* for both elements. To specify an arbitrary range, a value of
* <code>null</code> is used in place of an actual array of
* <code>Dimension</code>s.
*
* <p> If no array is specified on the constructor, but tiling is
* allowed, then this method returns <code>null</code>.
*
* @exception UnsupportedOperationException if the plug-in does
* not support tiling.
*
* @return an array of <code>Dimension</code>s with an even length
* of at least two, or <code>null</code>.
*/
public Dimension[] getPreferredTileSizes() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported");
}
return clonePreferredTileSizes(preferredTileSizes);
}
/** {@collect.stats}
* Specifies that the image should be tiled in the output stream.
* The <code>tileWidth</code> and <code>tileHeight</code>
* parameters specify the width and height of the tiles in the
* file. If the tile width or height is greater than the width or
* height of the image, the image is not tiled in that dimension.
*
* <p> If <code>canOffsetTiles</code> returns <code>false</code>,
* then the <code>tileGridXOffset</code> and
* <code>tileGridYOffset</code> parameters must be zero.
*
* @param tileWidth the width of each tile.
* @param tileHeight the height of each tile.
* @param tileGridXOffset the horizontal offset of the tile grid.
* @param tileGridYOffset the vertical offset of the tile grid.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
* @exception UnsupportedOperationException if the plug-in does not
* support grid offsets, and the grid offsets are not both zero.
* @exception IllegalArgumentException if the tile size is not
* within one of the allowable ranges returned by
* <code>getPreferredTileSizes</code>.
* @exception IllegalArgumentException if <code>tileWidth</code>
* or <code>tileHeight</code> is less than or equal to 0.
*
* @see #canWriteTiles
* @see #canOffsetTiles
* @see #getTileWidth()
* @see #getTileHeight()
* @see #getTileGridXOffset()
* @see #getTileGridYOffset()
*/
public void setTiling(int tileWidth,
int tileHeight,
int tileGridXOffset,
int tileGridYOffset) {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
if (tileWidth <= 0 || tileHeight <= 0) {
throw new IllegalArgumentException
("tile dimensions are non-positive!");
}
boolean tilesOffset = (tileGridXOffset != 0) || (tileGridYOffset != 0);
if (!canOffsetTiles() && tilesOffset) {
throw new UnsupportedOperationException("Can't offset tiles!");
}
if (preferredTileSizes != null) {
boolean ok = true;
for (int i = 0; i < preferredTileSizes.length; i += 2) {
Dimension min = preferredTileSizes[i];
Dimension max = preferredTileSizes[i+1];
if ((tileWidth < min.width) ||
(tileWidth > max.width) ||
(tileHeight < min.height) ||
(tileHeight > max.height)) {
ok = false;
break;
}
}
if (!ok) {
throw new IllegalArgumentException("Illegal tile size!");
}
}
this.tilingSet = true;
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.tileGridXOffset = tileGridXOffset;
this.tileGridYOffset = tileGridYOffset;
}
/** {@collect.stats}
* Removes any previous tile grid parameters specified by calls to
* <code>setTiling</code>.
*
* <p> The default implementation sets the instance variables
* <code>tileWidth</code>, <code>tileHeight</code>,
* <code>tileGridXOffset</code>, and
* <code>tileGridYOffset</code> to <code>0</code>.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
*
* @see #setTiling(int, int, int, int)
*/
public void unsetTiling() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
this.tilingSet = false;
this.tileWidth = 0;
this.tileHeight = 0;
this.tileGridXOffset = 0;
this.tileGridYOffset = 0;
}
/** {@collect.stats}
* Returns the width of each tile in an image as it will be
* written to the output stream. If tiling parameters have not
* been set, an <code>IllegalStateException</code> is thrown.
*
* @return the tile width to be used for encoding.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the tiling parameters have
* not been set.
*
* @see #setTiling(int, int, int, int)
* @see #getTileHeight()
*/
public int getTileWidth() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
if (!tilingSet) {
throw new IllegalStateException("Tiling parameters not set!");
}
return tileWidth;
}
/** {@collect.stats}
* Returns the height of each tile in an image as it will be written to
* the output stream. If tiling parameters have not
* been set, an <code>IllegalStateException</code> is thrown.
*
* @return the tile height to be used for encoding.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the tiling parameters have
* not been set.
*
* @see #setTiling(int, int, int, int)
* @see #getTileWidth()
*/
public int getTileHeight() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
if (!tilingSet) {
throw new IllegalStateException("Tiling parameters not set!");
}
return tileHeight;
}
/** {@collect.stats}
* Returns the horizontal tile grid offset of an image as it will
* be written to the output stream. If tiling parameters have not
* been set, an <code>IllegalStateException</code> is thrown.
*
* @return the tile grid X offset to be used for encoding.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the tiling parameters have
* not been set.
*
* @see #setTiling(int, int, int, int)
* @see #getTileGridYOffset()
*/
public int getTileGridXOffset() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
if (!tilingSet) {
throw new IllegalStateException("Tiling parameters not set!");
}
return tileGridXOffset;
}
/** {@collect.stats}
* Returns the vertical tile grid offset of an image as it will
* be written to the output stream. If tiling parameters have not
* been set, an <code>IllegalStateException</code> is thrown.
*
* @return the tile grid Y offset to be used for encoding.
*
* @exception UnsupportedOperationException if the plug-in does not
* support tiling.
* @exception IllegalStateException if the tiling mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the tiling parameters have
* not been set.
*
* @see #setTiling(int, int, int, int)
* @see #getTileGridXOffset()
*/
public int getTileGridYOffset() {
if (!canWriteTiles()) {
throw new UnsupportedOperationException("Tiling not supported!");
}
if (getTilingMode() != MODE_EXPLICIT) {
throw new IllegalStateException("Tiling mode not MODE_EXPLICIT!");
}
if (!tilingSet) {
throw new IllegalStateException("Tiling parameters not set!");
}
return tileGridYOffset;
}
/** {@collect.stats}
* Returns <code>true</code> if the writer can write out images
* as a series of passes of progressively increasing quality.
*
* @return <code>true</code> if the writer supports progressive
* encoding.
*
* @see #setProgressiveMode
* @see #getProgressiveMode
*/
public boolean canWriteProgressive() {
return canWriteProgressive;
}
/** {@collect.stats}
* Specifies that the writer is to write the image out in a
* progressive mode such that the stream will contain a series of
* scans of increasing quality. If progressive encoding is not
* supported, an <code>UnsupportedOperationException</code> will
* be thrown.
*
* <p> The mode argument determines how
* the progression parameters are chosen, and must be either
* <code>MODE_DISABLED</code>,
* <code>MODE_COPY_FROM_METADATA</code>, or
* <code>MODE_DEFAULT</code>. Otherwise an
* <code>IllegalArgumentException</code> is thrown.
*
* <p> The modes are interpreted as follows:
*
* <ul>
* <li><code>MODE_DISABLED</code> - No progression. Use this to
* turn off progession.
*
* <li><code>MODE_COPY_FROM_METADATA</code> - The output image
* will use whatever progression parameters are found in the
* metadata objects passed into the writer.
*
* <li><code>MODE_DEFAULT</code> - The image will be written
* progressively, with parameters chosen by the writer.
* </ul>
*
* <p> The default is <code>MODE_COPY_FROM_METADATA</code>.
*
* @param mode The mode for setting progression in the output
* stream.
*
* @exception UnsupportedOperationException if the writer does not
* support progressive encoding.
* @exception IllegalArgumentException if <code>mode</code> is not
* one of the modes listed above.
*
* @see #getProgressiveMode
*/
public void setProgressiveMode(int mode) {
if (!canWriteProgressive()) {
throw new UnsupportedOperationException(
"Progressive output not supported");
}
if (mode < MODE_DISABLED || mode > MAX_MODE) {
throw new IllegalArgumentException("Illegal value for mode!");
}
if (mode == MODE_EXPLICIT) {
throw new IllegalArgumentException(
"MODE_EXPLICIT not supported for progressive output");
}
this.progressiveMode = mode;
}
/** {@collect.stats}
* Returns the current mode for writing the stream in a
* progressive manner.
*
* @return the current mode for progressive encoding.
*
* @exception UnsupportedOperationException if the writer does not
* support progressive encoding.
*
* @see #setProgressiveMode
*/
public int getProgressiveMode() {
if (!canWriteProgressive()) {
throw new UnsupportedOperationException
("Progressive output not supported");
}
return progressiveMode;
}
/** {@collect.stats}
* Returns <code>true</code> if this writer supports compression.
*
* @return <code>true</code> if the writer supports compression.
*/
public boolean canWriteCompressed() {
return canWriteCompressed;
}
/** {@collect.stats}
* Specifies whether compression is to be performed, and if so how
* compression parameters are to be determined. The <code>mode</code>
* argument must be one of the four modes, interpreted as follows:
*
* <ul>
* <li><code>MODE_DISABLED</code> - If the mode is set to
* <code>MODE_DISABLED</code>, methods that query or modify the
* compression type or parameters will throw an
* <code>IllegalStateException</code> (if compression is
* normally supported by the plug-in). Some writers, such as JPEG,
* do not normally offer uncompressed output. In this case, attempting
* to set the mode to <code>MODE_DISABLED</code> will throw an
* <code>UnsupportedOperationException</code> and the mode will not be
* changed.
*
* <li><code>MODE_EXPLICIT</code> - Compress using the
* compression type and quality settings specified in this
* <code>ImageWriteParam</code>. Any previously set compression
* parameters are discarded.
*
* <li><code>MODE_COPY_FROM_METADATA</code> - Use whatever
* compression parameters are specified in metadata objects
* passed in to the writer.
*
* <li><code>MODE_DEFAULT</code> - Use default compression
* parameters.
* </ul>
*
* <p> The default is <code>MODE_COPY_FROM_METADATA</code>.
*
* @param mode The mode for setting compression in the output
* stream.
*
* @exception UnsupportedOperationException if the writer does not
* support compression, or does not support the requested mode.
* @exception IllegalArgumentException if <code>mode</code> is not
* one of the modes listed above.
*
* @see #getCompressionMode
*/
public void setCompressionMode(int mode) {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (mode < MODE_DISABLED || mode > MAX_MODE) {
throw new IllegalArgumentException("Illegal value for mode!");
}
this.compressionMode = mode;
if (mode == MODE_EXPLICIT) {
unsetCompression();
}
}
/** {@collect.stats}
* Returns the current compression mode, if compression is
* supported.
*
* @return the current compression mode.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
*
* @see #setCompressionMode
*/
public int getCompressionMode() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
return compressionMode;
}
/** {@collect.stats}
* Returns a list of available compression types, as an array or
* <code>String</code>s, or <code>null</code> if a compression
* type may not be chosen using these interfaces. The array
* returned is a copy.
*
* <p> If the writer only offers a single, mandatory form of
* compression, it is not necessary to provide any named
* compression types. Named compression types should only be
* used where the user is able to make a meaningful choice
* between different schemes.
*
* <p> The default implementation checks if compression is
* supported and throws an
* <code>UnsupportedOperationException</code> if not. Otherwise,
* it returns a clone of the <code>compressionTypes</code>
* instance variable if it is non-<code>null</code>, or else
* returns <code>null</code>.
*
* @return an array of <code>String</code>s containing the
* (non-localized) names of available compression types, or
* <code>null</code>.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
*/
public String[] getCompressionTypes() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported");
}
if (compressionTypes == null) {
return null;
}
return (String[])compressionTypes.clone();
}
/** {@collect.stats}
* Sets the compression type to one of the values indicated by
* <code>getCompressionTypes</code>. If a value of
* <code>null</code> is passed in, any previous setting is
* removed.
*
* <p> The default implementation checks whether compression is
* supported and the compression mode is
* <code>MODE_EXPLICIT</code>. If so, it calls
* <code>getCompressionTypes</code> and checks if
* <code>compressionType</code> is one of the legal values. If it
* is, the <code>compressionType</code> instance variable is set.
* If <code>compressionType</code> is <code>null</code>, the
* instance variable is set without performing any checking.
*
* @param compressionType one of the <code>String</code>s returned
* by <code>getCompressionTypes</code>, or <code>null</code> to
* remove any previous setting.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception UnsupportedOperationException if there are no
* settable compression types.
* @exception IllegalArgumentException if
* <code>compressionType</code> is non-<code>null</code> but is not
* one of the values returned by <code>getCompressionTypes</code>.
*
* @see #getCompressionTypes
* @see #getCompressionType
* @see #unsetCompression
*/
public void setCompressionType(String compressionType) {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
String[] legalTypes = getCompressionTypes();
if (legalTypes == null) {
throw new UnsupportedOperationException(
"No settable compression types");
}
if (compressionType != null) {
boolean found = false;
if (legalTypes != null) {
for (int i = 0; i < legalTypes.length; i++) {
if (compressionType.equals(legalTypes[i])) {
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("Unknown compression type!");
}
}
this.compressionType = compressionType;
}
/** {@collect.stats}
* Returns the currently set compression type, or
* <code>null</code> if none has been set. The type is returned
* as a <code>String</code> from among those returned by
* <code>getCompressionTypes</code>.
* If no compression type has been set, <code>null</code> is
* returned.
*
* <p> The default implementation checks whether compression is
* supported and the compression mode is
* <code>MODE_EXPLICIT</code>. If so, it returns the value of the
* <code>compressionType</code> instance variable.
*
* @return the current compression type as a <code>String</code>,
* or <code>null</code> if no type is set.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
*
* @see #setCompressionType
*/
public String getCompressionType() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
return compressionType;
}
/** {@collect.stats}
* Removes any previous compression type and quality settings.
*
* <p> The default implementation sets the instance variable
* <code>compressionType</code> to <code>null</code>, and the
* instance variable <code>compressionQuality</code> to
* <code>1.0F</code>.
*
* @exception UnsupportedOperationException if the plug-in does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
*
* @see #setCompressionType
* @see #setCompressionQuality
*/
public void unsetCompression() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
this.compressionType = null;
this.compressionQuality = 1.0F;
}
/** {@collect.stats}
* Returns a localized version of the name of the current
* compression type, using the <code>Locale</code> returned by
* <code>getLocale</code>.
*
* <p> The default implementation checks whether compression is
* supported and the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>compressionType</code> is <code>non-null</code> the value
* of <code>getCompressionType</code> is returned as a
* convenience.
*
* @return a <code>String</code> containing a localized version of
* the name of the current compression type.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if no compression type is set.
*/
public String getLocalizedCompressionTypeName() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if (getCompressionType() == null) {
throw new IllegalStateException("No compression type set!");
}
return getCompressionType();
}
/** {@collect.stats}
* Returns <code>true</code> if the current compression type
* provides lossless compression. If a plug-in provides only
* one mandatory compression type, then this method may be
* called without calling <code>setCompressionType</code> first.
*
* <p> If there are multiple compression types but none has
* been set, an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks whether compression is
* supported and the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> is <code>null</code> or
* <code>getCompressionType()</code> is non-<code>null</code>
* <code>true</code> is returned as a convenience.
*
* @return <code>true</code> if the current compression type is
* lossless.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
*/
public boolean isCompressionLossless() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return true;
}
/** {@collect.stats}
* Sets the compression quality to a value between <code>0</code>
* and <code>1</code>. Only a single compression quality setting
* is supported by default; writers can provide extended versions
* of <code>ImageWriteParam</code> that offer more control. For
* lossy compression schemes, the compression quality should
* control the tradeoff between file size and image quality (for
* example, by choosing quantization tables when writing JPEG
* images). For lossless schemes, the compression quality may be
* used to control the tradeoff between file size and time taken
* to perform the compression (for example, by optimizing row
* filters and setting the ZLIB compression level when writing
* PNG images).
*
* <p> A compression quality setting of 0.0 is most generically
* interpreted as "high compression is important," while a setting of
* 1.0 is most generically interpreted as "high image quality is
* important."
*
* <p> If there are multiple compression types but none has been
* set, an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks that compression is
* supported, and that the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> returns <code>null</code> or
* <code>compressionType</code> is non-<code>null</code> it sets
* the <code>compressionQuality</code> instance variable.
*
* @param quality a <code>float</code> between <code>0</code>and
* <code>1</code> indicating the desired quality level.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
* @exception IllegalArgumentException if <code>quality</code> is
* not between <code>0</code>and <code>1</code>, inclusive.
*
* @see #getCompressionQuality
*/
public void setCompressionQuality(float quality) {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if (getCompressionTypes() != null && getCompressionType() == null) {
throw new IllegalStateException("No compression type set!");
}
if (quality < 0.0F || quality > 1.0F) {
throw new IllegalArgumentException("Quality out-of-bounds!");
}
this.compressionQuality = quality;
}
/** {@collect.stats}
* Returns the current compression quality setting.
*
* <p> If there are multiple compression types but none has been
* set, an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks that compression is
* supported and that the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> is <code>null</code> or
* <code>getCompressionType()</code> is non-<code>null</code>, it
* returns the value of the <code>compressionQuality</code>
* instance variable.
*
* @return the current compression quality setting.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
*
* @see #setCompressionQuality
*/
public float getCompressionQuality() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return compressionQuality;
}
/** {@collect.stats}
* Returns a <code>float</code> indicating an estimate of the
* number of bits of output data for each bit of input image data
* at the given quality level. The value will typically lie
* between <code>0</code> and <code>1</code>, with smaller values
* indicating more compression. A special value of
* <code>-1.0F</code> is used to indicate that no estimate is
* available.
*
* <p> If there are multiple compression types but none has been set,
* an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks that compression is
* supported and the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> is <code>null</code> or
* <code>getCompressionType()</code> is non-<code>null</code>, and
* <code>quality</code> is within bounds, it returns
* <code>-1.0</code>.
*
* @param quality the quality setting whose bit rate is to be
* queried.
*
* @return an estimate of the compressed bit rate, or
* <code>-1.0F</code> if no estimate is available.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
* @exception IllegalArgumentException if <code>quality</code> is
* not between <code>0</code>and <code>1</code>, inclusive.
*/
public float getBitRate(float quality) {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
if (quality < 0.0F || quality > 1.0F) {
throw new IllegalArgumentException("Quality out-of-bounds!");
}
return -1.0F;
}
/** {@collect.stats}
* Returns an array of <code>String</code>s that may be used along
* with <code>getCompressionQualityValues</code> as part of a user
* interface for setting or displaying the compression quality
* level. The <code>String</code> with index <code>i</code>
* provides a description of the range of quality levels between
* <code>getCompressionQualityValues[i]</code> and
* <code>getCompressionQualityValues[i + 1]</code>. Note that the
* length of the array returned from
* <code>getCompressionQualityValues</code> will always be one
* greater than that returned from
* <code>getCompressionQualityDescriptions</code>.
*
* <p> As an example, the strings "Good", "Better", and "Best"
* could be associated with the ranges <code>[0, .33)</code>,
* <code>[.33, .66)</code>, and <code>[.66, 1.0]</code>. In this
* case, <code>getCompressionQualityDescriptions</code> would
* return <code>{ "Good", "Better", "Best" }</code> and
* <code>getCompressionQualityValues</code> would return
* <code>{ 0.0F, .33F, .66F, 1.0F }</code>.
*
* <p> If no descriptions are available, <code>null</code> is
* returned. If <code>null</code> is returned from
* <code>getCompressionQualityValues</code>, this method must also
* return <code>null</code>.
*
* <p> The descriptions should be localized for the
* <code>Locale</code> returned by <code>getLocale</code>, if it
* is non-<code>null</code>.
*
* <p> If there are multiple compression types but none has been set,
* an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks that compression is
* supported and that the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> is <code>null</code> or
* <code>getCompressionType()</code> is non-<code>null</code>, it
* returns <code>null</code>.
*
* @return an array of <code>String</code>s containing localized
* descriptions of the compression quality levels.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
*
* @see #getCompressionQualityValues
*/
public String[] getCompressionQualityDescriptions() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return null;
}
/** {@collect.stats}
* Returns an array of <code>float</code>s that may be used along
* with <code>getCompressionQualityDescriptions</code> as part of a user
* interface for setting or displaying the compression quality
* level. See {@link #getCompressionQualityDescriptions
* <code>getCompressionQualityDescriptions</code>} for more information.
*
* <p> If no descriptions are available, <code>null</code> is
* returned. If <code>null</code> is returned from
* <code>getCompressionQualityDescriptions</code>, this method
* must also return <code>null</code>.
*
* <p> If there are multiple compression types but none has been set,
* an <code>IllegalStateException</code> is thrown.
*
* <p> The default implementation checks that compression is
* supported and that the compression mode is
* <code>MODE_EXPLICIT</code>. If so, if
* <code>getCompressionTypes()</code> is <code>null</code> or
* <code>getCompressionType()</code> is non-<code>null</code>, it
* returns <code>null</code>.
*
* @return an array of <code>float</code>s indicating the
* boundaries between the compression quality levels as described
* by the <code>String</code>s from
* <code>getCompressionQualityDescriptions</code>.
*
* @exception UnsupportedOperationException if the writer does not
* support compression.
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
* @exception IllegalStateException if the set of legal
* compression types is non-<code>null</code> and the current
* compression type is <code>null</code>.
*
* @see #getCompressionQualityDescriptions
*/
public float[] getCompressionQualityValues() {
if (!canWriteCompressed()) {
throw new UnsupportedOperationException(
"Compression not supported.");
}
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return null;
}
}
|
Java
|
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.bmp;
import java.util.Locale;
import javax.imageio.ImageWriteParam;
import com.sun.imageio.plugins.bmp.BMPConstants;
/** {@collect.stats}
* A subclass of <code>ImageWriteParam</code> for encoding images in
* the BMP format.
*
* <p> This class allows for the specification of various parameters
* while writing a BMP format image file. By default, the data layout
* is bottom-up, such that the pixels are stored in bottom-up order,
* the first scanline being stored last.
*
* <p>The particular compression scheme to be used can be specified by using
* the <code>setCompressionType()</code> method with the appropriate type
* string. The compression scheme specified will be honored if and only if it
* is compatible with the type of image being written. If the specified
* compression scheme is not compatible with the type of image being written
* then the <code>IOException</code> will be thrown by the BMP image writer.
* If the compression type is not set explicitly then <code>getCompressionType()</code>
* will return <code>null</code>. In this case the BMP image writer will select
* a compression type that supports encoding of the given image without loss
* of the color resolution.
* <p>The compression type strings and the image type(s) each supports are
* listed in the following
* table:
*
* <p><table border=1>
* <caption><b>Compression Types</b></caption>
* <tr><th>Type String</th> <th>Description</th> <th>Image Types</th></tr>
* <tr><td>BI_RGB</td> <td>Uncompressed RLE</td> <td><= 8-bits/sample</td></tr>
* <tr><td>BI_RLE8</td> <td>8-bit Run Length Encoding</td> <td><= 8-bits/sample</td></tr>
* <tr><td>BI_RLE4</td> <td>4-bit Run Length Encoding</td> <td><= 4-bits/sample</td></tr>
* <tr><td>BI_BITFIELDS</td> <td>Packed data</td> <td> 16 or 32 bits/sample</td></tr>
* </table>
*/
public class BMPImageWriteParam extends ImageWriteParam {
private boolean topDown = false;
/** {@collect.stats}
* Constructs a <code>BMPImageWriteParam</code> set to use a given
* <code>Locale</code> and with default values for all parameters.
*
* @param locale a <code>Locale</code> to be used to localize
* compression type names and quality descriptions, or
* <code>null</code>.
*/
public BMPImageWriteParam(Locale locale) {
super(locale);
// Set compression types ("BI_RGB" denotes uncompressed).
compressionTypes = BMPConstants.compressionTypeNames.clone();
// Set compression flag.
canWriteCompressed = true;
compressionMode = MODE_COPY_FROM_METADATA;
compressionType = compressionTypes[BMPConstants.BI_RGB];
}
/** {@collect.stats}
* Constructs an <code>BMPImageWriteParam</code> object with default
* values for all parameters and a <code>null</code> <code>Locale</code>.
*/
public BMPImageWriteParam() {
this(null);
}
/** {@collect.stats}
* If set, the data will be written out in a top-down manner, the first
* scanline being written first.
*
* @param topDown whether the data are written in top-down order.
*/
public void setTopDown(boolean topDown) {
this.topDown = topDown;
}
/** {@collect.stats}
* Returns the value of the <code>topDown</code> parameter.
* The default is <code>false</code>.
*
* @return whether the data are written in top-down order.
*/
public boolean isTopDown() {
return topDown;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.jpeg;
import java.util.Locale;
import javax.imageio.ImageWriteParam;
import com.sun.imageio.plugins.jpeg.JPEG;
/** {@collect.stats}
* This class adds the ability to set JPEG quantization and Huffman
* tables when using the built-in JPEG writer plug-in, and to request that
* optimized Huffman tables be computed for an image. An instance of
* this class will be returned from the
* <code>getDefaultImageWriteParam</code> methods of the built-in JPEG
* <code>ImageWriter</code>.
* <p> The principal purpose of these additions is to allow the
* specification of tables to use in encoding abbreviated streams.
* The built-in JPEG writer will also accept an ordinary
* <code>ImageWriteParam</code>, in which case the writer will
* construct the necessary tables internally.
*
* <p> In either case, the quality setting in an <code>ImageWriteParam</code>
* has the same meaning as for the underlying library: 1.00 means a
* quantization table of all 1's, 0.75 means the "standard", visually
* lossless quantization table, and 0.00 means aquantization table of
* all 255's.
*
* <p> While tables for abbreviated streams are often specified by
* first writing an abbreviated stream containing only the tables, in
* some applications the tables are fixed ahead of time. This class
* allows the tables to be specified directly from client code.
*
* <p> Normally, the tables are specified in the
* <code>IIOMetadata</code> objects passed in to the writer, and any
* tables included in these objects are written to the stream.
* If no tables are specified in the metadata, then an abbreviated
* stream is written. If no tables are included in the metadata and
* no tables are specified in a <code>JPEGImageWriteParam</code>, then
* an abbreviated stream is encoded using the "standard" visually
* lossless tables. This class is necessary for specifying tables
* when an abbreviated stream must be written without writing any tables
* to a stream first. In order to use this class, the metadata object
* passed into the writer must contain no tables, and no stream metadata
* must be provided. See {@link JPEGQTable <code>JPEGQTable</code>} and
* {@link JPEGHuffmanTable <code>JPEGHuffmanTable</code>} for more
* information on the default tables.
*
* <p> The default <code>JPEGImageWriteParam</code> returned by the
* <code>getDefaultWriteParam</code> method of the writer contains no
* tables. Default tables are included in the default
* <code>IIOMetadata</code> objects returned by the writer.
*
* <p> If the metadata does contain tables, the tables given in a
* <code>JPEGImageWriteParam</code> are ignored. Furthermore, once a
* set of tables has been written, only tables in the metadata can
* override them for subsequent writes, whether to the same stream or
* a different one. In order to specify new tables using this class,
* the {@link javax.imageio.ImageWriter#reset <code>reset</code>}
* method of the writer must be called.
*
* <p>
* For more information about the operation of the built-in JPEG plug-ins,
* see the <A HREF="../../metadata/doc-files/jpeg_metadata.html">JPEG
* metadata format specification and usage notes</A>.
*
*/
public class JPEGImageWriteParam extends ImageWriteParam {
private JPEGQTable[] qTables = null;
private JPEGHuffmanTable[] DCHuffmanTables = null;
private JPEGHuffmanTable[] ACHuffmanTables = null;
private boolean optimizeHuffman = false;
private String[] compressionNames = {"JPEG"};
private float[] qualityVals = { 0.00F, 0.30F, 0.75F, 1.00F };
private String[] qualityDescs = {
"Low quality", // 0.00 -> 0.30
"Medium quality", // 0.30 -> 0.75
"Visually lossless" // 0.75 -> 1.00
};
/** {@collect.stats}
* Constructs a <code>JPEGImageWriteParam</code>. Tiling is not
* supported. Progressive encoding is supported. The default
* progressive mode is MODE_DISABLED. A single form of compression,
* named "JPEG", is supported. The default compression quality is
* 0.75.
*
* @param locale a <code>Locale</code> to be used by the
* superclass to localize compression type names and quality
* descriptions, or <code>null</code>.
*/
public JPEGImageWriteParam(Locale locale) {
super(locale);
this.canWriteProgressive = true;
this.progressiveMode = MODE_DISABLED;
this.canWriteCompressed = true;
this.compressionTypes = compressionNames;
this.compressionType = compressionTypes[0];
this.compressionQuality = JPEG.DEFAULT_QUALITY;
}
/** {@collect.stats}
* Removes any previous compression quality setting.
*
* <p> The default implementation resets the compression quality
* to <code>0.75F</code>.
*
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
*/
public void unsetCompression() {
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
this.compressionQuality = JPEG.DEFAULT_QUALITY;
}
/** {@collect.stats}
* Returns <code>false</code> since the JPEG plug-in only supports
* lossy compression.
*
* @return <code>false</code>.
*
* @exception IllegalStateException if the compression mode is not
* <code>MODE_EXPLICIT</code>.
*/
public boolean isCompressionLossless() {
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
return false;
}
public String[] getCompressionQualityDescriptions() {
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return (String[])qualityDescs.clone();
}
public float[] getCompressionQualityValues() {
if (getCompressionMode() != MODE_EXPLICIT) {
throw new IllegalStateException
("Compression mode not MODE_EXPLICIT!");
}
if ((getCompressionTypes() != null) &&
(getCompressionType() == null)) {
throw new IllegalStateException("No compression type set!");
}
return (float[])qualityVals.clone();
}
/** {@collect.stats}
* Returns <code>true</code> if tables are currently set.
*
* @return <code>true</code> if tables are present.
*/
public boolean areTablesSet() {
return (qTables != null);
}
/** {@collect.stats}
* Sets the quantization and Huffman tables to use in encoding
* abbreviated streams. There may be a maximum of 4 tables of
* each type. These tables are ignored if tables are specified in
* the metadata. All arguments must be non-<code>null</code>.
* The two arrays of Huffman tables must have the same number of
* elements. The table specifiers in the frame and scan headers
* in the metadata are assumed to be equivalent to indices into
* these arrays. The argument arrays are copied by this method.
*
* @param qTables An array of quantization table objects.
* @param DCHuffmanTables An array of Huffman table objects.
* @param ACHuffmanTables An array of Huffman table objects.
*
* @exception IllegalArgumentException if any of the arguments
* is <code>null</code> or has more than 4 elements, or if the
* numbers of DC and AC tables differ.
*
* @see #unsetEncodeTables
*/
public void setEncodeTables(JPEGQTable[] qTables,
JPEGHuffmanTable[] DCHuffmanTables,
JPEGHuffmanTable[] ACHuffmanTables) {
if ((qTables == null) ||
(DCHuffmanTables == null) ||
(ACHuffmanTables == null) ||
(qTables.length > 4) ||
(DCHuffmanTables.length > 4) ||
(ACHuffmanTables.length > 4) ||
(DCHuffmanTables.length != ACHuffmanTables.length)) {
throw new IllegalArgumentException("Invalid JPEG table arrays");
}
this.qTables = (JPEGQTable[])qTables.clone();
this.DCHuffmanTables = (JPEGHuffmanTable[])DCHuffmanTables.clone();
this.ACHuffmanTables = (JPEGHuffmanTable[])ACHuffmanTables.clone();
}
/** {@collect.stats}
* Removes any quantization and Huffman tables that are currently
* set.
*
* @see #setEncodeTables
*/
public void unsetEncodeTables() {
this.qTables = null;
this.DCHuffmanTables = null;
this.ACHuffmanTables = null;
}
/** {@collect.stats}
* Returns a copy of the array of quantization tables set on the
* most recent call to <code>setEncodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGQTable</code> objects, or
* <code>null</code>.
*
* @see #setEncodeTables
*/
public JPEGQTable[] getQTables() {
return (qTables != null) ? (JPEGQTable[])qTables.clone() : null;
}
/** {@collect.stats}
* Returns a copy of the array of DC Huffman tables set on the
* most recent call to <code>setEncodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGHuffmanTable</code> objects, or
* <code>null</code>.
*
* @see #setEncodeTables
*/
public JPEGHuffmanTable[] getDCHuffmanTables() {
return (DCHuffmanTables != null)
? (JPEGHuffmanTable[])DCHuffmanTables.clone()
: null;
}
/** {@collect.stats}
* Returns a copy of the array of AC Huffman tables set on the
* most recent call to <code>setEncodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGHuffmanTable</code> objects, or
* <code>null</code>.
*
* @see #setEncodeTables
*/
public JPEGHuffmanTable[] getACHuffmanTables() {
return (ACHuffmanTables != null)
? (JPEGHuffmanTable[])ACHuffmanTables.clone()
: null;
}
/** {@collect.stats}
* Tells the writer to generate optimized Huffman tables
* for the image as part of the writing process. The
* default is <code>false</code>. If this flag is set
* to <code>true</code>, it overrides any tables specified
* in the metadata. Note that this means that any image
* written with this flag set to <code>true</code> will
* always contain Huffman tables.
*
* @param optimize A boolean indicating whether to generate
* optimized Huffman tables when writing.
*
* @see #getOptimizeHuffmanTables
*/
public void setOptimizeHuffmanTables(boolean optimize) {
optimizeHuffman = optimize;
}
/** {@collect.stats}
* Returns the value passed into the most recent call
* to <code>setOptimizeHuffmanTables</code>, or
* <code>false</code> if <code>setOptimizeHuffmanTables</code>
* has never been called.
*
* @return <code>true</code> if the writer will generate optimized
* Huffman tables.
*
* @see #setOptimizeHuffmanTables
*/
public boolean getOptimizeHuffmanTables() {
return optimizeHuffman;
}
}
|
Java
|
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.jpeg;
import java.util.Arrays;
/** {@collect.stats}
* A class encapsulating a single JPEG Huffman table.
* Fields are provided for the "standard" tables taken
* from Annex K of the JPEG specification.
* These are the tables used as defaults.
* <p>
* For more information about the operation of the standard JPEG plug-in,
* see the <A HREF="../../metadata/doc-files/jpeg_metadata.html">JPEG
* metadata format specification and usage notes</A>
*/
public class JPEGHuffmanTable {
/* The data for the publically defined tables, as specified in ITU T.81
* JPEG specification section K3.3 and used in the IJG library.
*/
private static final short[] StdDCLuminanceLengths = {
0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
private static final short[] StdDCLuminanceValues = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
};
private static final short[] StdDCChrominanceLengths = {
0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};
private static final short[] StdDCChrominanceValues = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
};
private static final short[] StdACLuminanceLengths = {
0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d,
};
private static final short[] StdACLuminanceValues = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa,
};
private static final short[] StdACChrominanceLengths = {
0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04,
0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77,
};
private static final short[] StdACChrominanceValues = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa,
};
/** {@collect.stats}
* The standard DC luminance Huffman table.
*/
public static final JPEGHuffmanTable
StdDCLuminance = new JPEGHuffmanTable(StdDCLuminanceLengths,
StdDCLuminanceValues, false);
/** {@collect.stats}
* The standard DC chrominance Huffman table.
*/
public static final JPEGHuffmanTable
StdDCChrominance = new JPEGHuffmanTable(StdDCChrominanceLengths,
StdDCChrominanceValues, false);
/** {@collect.stats}
* The standard AC luminance Huffman table.
*/
public static final JPEGHuffmanTable
StdACLuminance = new JPEGHuffmanTable(StdACLuminanceLengths,
StdACLuminanceValues, false);
/** {@collect.stats}
* The standard AC chrominance Huffman table.
*/
public static final JPEGHuffmanTable
StdACChrominance = new JPEGHuffmanTable(StdACChrominanceLengths,
StdACChrominanceValues, false);
private short[] lengths;
private short[] values;
/** {@collect.stats}
* Creates a Huffman table and initializes it. The input arrays are copied.
* The arrays must describe a possible Huffman table.
* For example, 3 codes cannot be expressed with a single bit.
*
* @param lengths an array of {@code short}s where <code>lengths[k]</code>
* is equal to the number of values with corresponding codes of
* length <code>k + 1</code> bits.
* @param values an array of shorts containing the values in
* order of increasing code length.
* @throws IllegalArgumentException if <code>lengths</code> or
* <code>values</code> are null, the length of <code>lengths</code> is
* greater than 16, the length of <code>values</code> is greater than 256,
* if any value in <code>lengths</code> or <code>values</code> is less
* than zero, or if the arrays do not describe a valid Huffman table.
*/
public JPEGHuffmanTable(short[] lengths, short[] values) {
if (lengths == null || values == null ||
lengths.length == 0 || values.length == 0 ||
lengths.length > 16 || values.length > 256) {
throw new IllegalArgumentException("Illegal lengths or values");
}
for (int i = 0; i<lengths.length; i++) {
if (lengths[i] < 0) {
throw new IllegalArgumentException("lengths["+i+"] < 0");
}
}
for (int i = 0; i<values.length; i++) {
if (values[i] < 0) {
throw new IllegalArgumentException("values["+i+"] < 0");
}
}
this.lengths = Arrays.copyOf(lengths, lengths.length);
this.values = Arrays.copyOf(values, values.length);
validate();
}
private void validate() {
int sumOfLengths = 0;
for (int i=0; i<lengths.length; i++) {
sumOfLengths += lengths[i];
}
if (sumOfLengths != values.length) {
throw new IllegalArgumentException("lengths do not correspond " +
"to length of value table");
}
}
/* Internal version which avoids the overhead of copying and checking */
private JPEGHuffmanTable(short[] lengths, short[] values, boolean copy) {
if (copy) {
this.lengths = Arrays.copyOf(lengths, lengths.length);
this.values = Arrays.copyOf(values, values.length);
} else {
this.lengths = lengths;
this.values = values;
}
}
/** {@collect.stats}
* Returns an array of <code>short</code>s containing the number of values
* for each length in the Huffman table. The returned array is a copy.
*
* @return a <code>short</code> array where <code>array[k-1]</code>
* is equal to the number of values in the table of length <code>k</code>.
* @see #getValues
*/
public short[] getLengths() {
return Arrays.copyOf(lengths, lengths.length);
}
/** {@collect.stats}
* Returns an array of <code>short</code>s containing the values arranged
* by increasing length of their corresponding codes.
* The interpretation of the array is dependent on the values returned
* from <code>getLengths</code>. The returned array is a copy.
*
* @return a <code>short</code> array of values.
* @see #getLengths
*/
public short[] getValues() {
return Arrays.copyOf(values, values.length);
}
/** {@collect.stats}
* Returns a {@code String} representing this Huffman table.
* @return a {@code String} representing this Huffman table.
*/
public String toString() {
String ls = System.getProperty("line.separator", "\n");
StringBuilder sb = new StringBuilder("JPEGHuffmanTable");
sb.append(ls).append("lengths:");
for (int i=0; i<lengths.length; i++) {
sb.append(" ").append(lengths[i]);
}
sb.append(ls).append("values:");
for (int i=0; i<values.length; i++) {
sb.append(" ").append(values[i]);
}
return sb.toString();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.jpeg;
import javax.imageio.ImageReadParam;
/** {@collect.stats}
* This class adds the ability to set JPEG quantization and Huffman
* tables when using the built-in JPEG reader plug-in. An instance of
* this class will be returned from the
* <code>getDefaultImageReadParam</code> methods of the built-in JPEG
* <code>ImageReader</code>.
*
* <p> The sole purpose of these additions is to allow the
* specification of tables for use in decoding abbreviated streams.
* The built-in JPEG reader will also accept an ordinary
* <code>ImageReadParam</code>, which is sufficient for decoding
* non-abbreviated streams.
*
* <p> While tables for abbreviated streams are often obtained by
* first reading another abbreviated stream containing only the
* tables, in some applications the tables are fixed ahead of time.
* This class allows the tables to be specified directly from client
* code. If no tables are specified either in the stream or in a
* <code>JPEGImageReadParam</code>, then the stream is presumed to use
* the "standard" visually lossless tables. See {@link JPEGQTable
* <code>JPEGQTable</code>} and {@link JPEGHuffmanTable
* <code>JPEGHuffmanTable</code>} for more information on the default
* tables.
*
* <p> The default <code>JPEGImageReadParam</code> returned by the
* <code>getDefaultReadParam</code> method of the builtin JPEG reader
* contains no tables. Default tables may be obtained from the table
* classes {@link JPEGQTable <code>JPEGQTable</code>} and {@link
* JPEGHuffmanTable <code>JPEGHuffmanTable</code>}.
*
* <p> If a stream does contain tables, the tables given in a
* <code>JPEGImageReadParam</code> are ignored. Furthermore, if the
* first image in a stream does contain tables and subsequent ones do
* not, then the tables given in the first image are used for all the
* abbreviated images. Once tables have been read from a stream, they
* can be overridden only by tables subsequently read from the same
* stream. In order to specify new tables, the {@link
* javax.imageio.ImageReader#setInput <code>setInput</code>} method of
* the reader must be called to change the stream.
*
* <p> Note that this class does not provide a means for obtaining the
* tables found in a stream. These may be extracted from a stream by
* consulting the <code>IIOMetadata</code> object returned by the
* reader.
*
* <p>
* For more information about the operation of the built-in JPEG plug-ins,
* see the <A HREF="../../metadata/doc-files/jpeg_metadata.html">JPEG
* metadata format specification and usage notes</A>.
*
*/
public class JPEGImageReadParam extends ImageReadParam {
private JPEGQTable[] qTables = null;
private JPEGHuffmanTable[] DCHuffmanTables = null;
private JPEGHuffmanTable[] ACHuffmanTables = null;
/** {@collect.stats}
* Constructs a <code>JPEGImageReadParam</code>.
*/
public JPEGImageReadParam() {
super();
}
/** {@collect.stats}
* Returns <code>true</code> if tables are currently set.
*
* @return <code>true</code> if tables are present.
*/
public boolean areTablesSet() {
return (qTables != null);
}
/** {@collect.stats}
* Sets the quantization and Huffman tables to use in decoding
* abbreviated streams. There may be a maximum of 4 tables of
* each type. These tables are ignored once tables are
* encountered in the stream. All arguments must be
* non-<code>null</code>. The two arrays of Huffman tables must
* have the same number of elements. The table specifiers in the
* frame and scan headers in the stream are assumed to be
* equivalent to indices into these arrays. The argument arrays
* are copied by this method.
*
* @param qTables an array of quantization table objects.
* @param DCHuffmanTables an array of Huffman table objects.
* @param ACHuffmanTables an array of Huffman table objects.
*
* @exception IllegalArgumentException if any of the arguments
* is <code>null</code>, has more than 4 elements, or if the
* numbers of DC and AC tables differ.
*
* @see #unsetDecodeTables
*/
public void setDecodeTables(JPEGQTable[] qTables,
JPEGHuffmanTable[] DCHuffmanTables,
JPEGHuffmanTable[] ACHuffmanTables) {
if ((qTables == null) ||
(DCHuffmanTables == null) ||
(ACHuffmanTables == null) ||
(qTables.length > 4) ||
(DCHuffmanTables.length > 4) ||
(ACHuffmanTables.length > 4) ||
(DCHuffmanTables.length != ACHuffmanTables.length)) {
throw new IllegalArgumentException
("Invalid JPEG table arrays");
}
this.qTables = (JPEGQTable[])qTables.clone();
this.DCHuffmanTables = (JPEGHuffmanTable[])DCHuffmanTables.clone();
this.ACHuffmanTables = (JPEGHuffmanTable[])ACHuffmanTables.clone();
}
/** {@collect.stats}
* Removes any quantization and Huffman tables that are currently
* set.
*
* @see #setDecodeTables
*/
public void unsetDecodeTables() {
this.qTables = null;
this.DCHuffmanTables = null;
this.ACHuffmanTables = null;
}
/** {@collect.stats}
* Returns a copy of the array of quantization tables set on the
* most recent call to <code>setDecodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGQTable</code> objects, or
* <code>null</code>.
*
* @see #setDecodeTables
*/
public JPEGQTable[] getQTables() {
return (qTables != null) ? (JPEGQTable[])qTables.clone() : null;
}
/** {@collect.stats}
* Returns a copy of the array of DC Huffman tables set on the
* most recent call to <code>setDecodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGHuffmanTable</code> objects, or
* <code>null</code>.
*
* @see #setDecodeTables
*/
public JPEGHuffmanTable[] getDCHuffmanTables() {
return (DCHuffmanTables != null)
? (JPEGHuffmanTable[])DCHuffmanTables.clone()
: null;
}
/** {@collect.stats}
* Returns a copy of the array of AC Huffman tables set on the
* most recent call to <code>setDecodeTables</code>, or
* <code>null</code> if tables are not currently set.
*
* @return an array of <code>JPEGHuffmanTable</code> objects, or
* <code>null</code>.
*
* @see #setDecodeTables
*/
public JPEGHuffmanTable[] getACHuffmanTables() {
return (ACHuffmanTables != null)
? (JPEGHuffmanTable[])ACHuffmanTables.clone()
: null;
}
}
|
Java
|
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.plugins.jpeg;
import java.util.Arrays;
/** {@collect.stats}
* A class encapsulating a single JPEG quantization table.
* The elements appear in natural order (as opposed to zig-zag order).
* Static variables are provided for the "standard" tables taken from
* Annex K of the JPEG specification, as well as the default tables
* conventionally used for visually lossless encoding.
* <p>
* For more information about the operation of the standard JPEG plug-in,
* see the <A HREF="../../metadata/doc-files/jpeg_metadata.html">JPEG
* metadata format specification and usage notes</A>
*/
public class JPEGQTable {
private static final int[] k1 = {
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99,
};
private static final int[] k1div2 = {
8, 6, 5, 8, 12, 20, 26, 31,
6, 6, 7, 10, 13, 29, 30, 28,
7, 7, 8, 12, 20, 29, 35, 28,
7, 9, 11, 15, 26, 44, 40, 31,
9, 11, 19, 28, 34, 55, 52, 39,
12, 18, 28, 32, 41, 52, 57, 46,
25, 32, 39, 44, 52, 61, 60, 51,
36, 46, 48, 49, 56, 50, 52, 50,
};
private static final int[] k2 = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
};
private static final int[] k2div2 = {
9, 9, 12, 24, 50, 50, 50, 50,
9, 11, 13, 33, 50, 50, 50, 50,
12, 13, 28, 50, 50, 50, 50, 50,
24, 33, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
50, 50, 50, 50, 50, 50, 50, 50,
};
/** {@collect.stats}
* The sample luminance quantization table given in the JPEG
* specification, table K.1. According to the specification,
* these values produce "good" quality output.
* @see #K1Div2Luminance
*/
public static final JPEGQTable
K1Luminance = new JPEGQTable(k1, false);
/** {@collect.stats}
* The sample luminance quantization table given in the JPEG
* specification, table K.1, with all elements divided by 2.
* According to the specification, these values produce "very good"
* quality output. This is the table usually used for "visually lossless"
* encoding, and is the default luminance table used if the default
* tables and quality settings are used.
* @see #K1Luminance
*/
public static final JPEGQTable
K1Div2Luminance = new JPEGQTable(k1div2, false);
/** {@collect.stats}
* The sample chrominance quantization table given in the JPEG
* specification, table K.2. According to the specification,
* these values produce "good" quality output.
* @see #K2Div2Chrominance
*/
public static final JPEGQTable K2Chrominance =
new JPEGQTable(k2, false);
/** {@collect.stats}
* The sample chrominance quantization table given in the JPEG
* specification, table K.1, with all elements divided by 2.
* According to the specification, these values produce "very good"
* quality output. This is the table usually used for "visually lossless"
* encoding, and is the default chrominance table used if the default
* tables and quality settings are used.
* @see #K2Chrominance
*/
public static final JPEGQTable K2Div2Chrominance =
new JPEGQTable(k2div2, false);
private int[] qTable;
private JPEGQTable(int[] table, boolean copy) {
qTable = (copy) ? Arrays.copyOf(table, table.length) : table;
}
/** {@collect.stats}
* Constructs a quantization table from the argument, which must
* contain 64 elements in natural order (not zig-zag order).
* A copy is made of the the input array.
* @param table the quantization table, as an <code>int</code> array.
* @throws IllegalArgumentException if <code>table</code> is
* <code>null</code> or <code>table.length</code> is not equal to 64.
*/
public JPEGQTable(int[] table) {
if (table == null) {
throw new IllegalArgumentException("table must not be null.");
}
if (table.length != 64) {
throw new IllegalArgumentException("table.length != 64");
}
qTable = Arrays.copyOf(table, table.length);
}
/** {@collect.stats}
* Returns a copy of the current quantization table as an array
* of {@code int}s in natural (not zig-zag) order.
* @return A copy of the current quantization table.
*/
public int[] getTable() {
return Arrays.copyOf(qTable, qTable.length);
}
/** {@collect.stats}
* Returns a new quantization table where the values are multiplied
* by <code>scaleFactor</code> and then clamped to the range 1..32767
* (or to 1..255 if <code>forceBaseline</code> is true).
* <p>
* Values of <code>scaleFactor</code> less than 1 tend to improve
* the quality level of the table, and values greater than 1.0
* degrade the quality level of the table.
* @param scaleFactor multiplication factor for the table.
* @param forceBaseline if <code>true</code>,
* the values will be clamped to the range 1..255
* @return a new quantization table that is a linear multiple
* of the current table.
*/
public JPEGQTable getScaledInstance(float scaleFactor,
boolean forceBaseline) {
int max = (forceBaseline) ? 255 : 32767;
int[] scaledTable = new int[qTable.length];
for (int i=0; i<qTable.length; i++) {
int sv = (int)((qTable[i] * scaleFactor)+0.5f);
if (sv < 1) {
sv = 1;
}
if (sv > max) {
sv = max;
}
scaledTable[i] = sv;
}
return new JPEGQTable(scaledTable);
}
/** {@collect.stats}
* Returns a {@code String} representing this quantization table.
* @return a {@code String} representing this quantization table.
*/
public String toString() {
String ls = System.getProperty("line.separator", "\n");
StringBuilder sb = new StringBuilder("JPEGQTable:"+ls);
for (int i=0; i < qTable.length; i++) {
if (i % 8 == 0) {
sb.append('\t');
}
sb.append(qTable[i]);
sb.append(((i % 8) == 7) ? ls : ' ');
}
return sb.toString();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.event;
import java.util.EventListener;
import javax.imageio.ImageReader;
/** {@collect.stats}
* An interface used by <code>ImageReader</code> implementations to
* notify callers of their image and thumbnail reading methods of
* progress.
*
* <p> This interface receives general indications of decoding
* progress (via the <code>imageProgress</code> and
* <code>thumbnailProgress</code> methods), and events indicating when
* an entire image has been updated (via the
* <code>imageStarted</code>, <code>imageComplete</code>,
* <code>thumbnailStarted</code> and <code>thumbnailComplete</code>
* methods). Applications that wish to be informed of pixel updates
* as they happen (for example, during progressive decoding), should
* provide an <code>IIOReadUpdateListener</code>.
*
* @see IIOReadUpdateListener
* @see javax.imageio.ImageReader#addIIOReadProgressListener
* @see javax.imageio.ImageReader#removeIIOReadProgressListener
*
*/
public interface IIOReadProgressListener extends EventListener {
/** {@collect.stats}
* Reports that a sequence of read operations is beginning.
* <code>ImageReader</code> implementations are required to call
* this method exactly once from their
* <code>readAll(Iterator)</code> method.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param minIndex the index of the first image to be read.
*/
void sequenceStarted(ImageReader source, int minIndex);
/** {@collect.stats}
* Reports that a sequence of read operationshas completed.
* <code>ImageReader</code> implementations are required to call
* this method exactly once from their
* <code>readAll(Iterator)</code> method.
*
* @param source the <code>ImageReader</code> object calling this method.
*/
void sequenceComplete(ImageReader source);
/** {@collect.stats}
* Reports that an image read operation is beginning. All
* <code>ImageReader</code> implementations are required to call
* this method exactly once when beginning an image read
* operation.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param imageIndex the index of the image being read within its
* containing input file or stream.
*/
void imageStarted(ImageReader source, int imageIndex);
/** {@collect.stats}
* Reports the approximate degree of completion of the current
* <code>read</code> call of the associated
* <code>ImageReader</code>.
*
* <p> The degree of completion is expressed as a percentage
* varying from <code>0.0F</code> to <code>100.0F</code>. The
* percentage should ideally be calculated in terms of the
* remaining time to completion, but it is usually more practical
* to use a more well-defined metric such as pixels decoded or
* portion of input stream consumed. In any case, a sequence of
* calls to this method during a given read operation should
* supply a monotonically increasing sequence of percentage
* values. It is not necessary to supply the exact values
* <code>0</code> and <code>100</code>, as these may be inferred
* by the callee from other methods.
*
* <p> Each particular <code>ImageReader</code> implementation may
* call this method at whatever frequency it desires. A rule of
* thumb is to call it around each 5 percent mark.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param percentageDone the approximate percentage of decoding that
* has been completed.
*/
void imageProgress(ImageReader source, float percentageDone);
/** {@collect.stats}
* Reports that the current image read operation has completed.
* All <code>ImageReader</code> implementations are required to
* call this method exactly once upon completion of each image
* read operation.
*
* @param source the <code>ImageReader</code> object calling this
* method.
*/
void imageComplete(ImageReader source);
/** {@collect.stats}
* Reports that a thumbnail read operation is beginning. All
* <code>ImageReader</code> implementations are required to call
* this method exactly once when beginning a thumbnail read
* operation.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param imageIndex the index of the image being read within its
* containing input file or stream.
* @param thumbnailIndex the index of the thumbnail being read.
*/
void thumbnailStarted(ImageReader source,
int imageIndex, int thumbnailIndex);
/** {@collect.stats}
* Reports the approximate degree of completion of the current
* <code>getThumbnail</code> call within the associated
* <code>ImageReader</code>. The semantics are identical to those
* of <code>imageProgress</code>.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param percentageDone the approximate percentage of decoding that
* has been completed.
*/
void thumbnailProgress(ImageReader source, float percentageDone);
/** {@collect.stats}
* Reports that a thumbnail read operation has completed. All
* <code>ImageReader</code> implementations are required to call
* this method exactly once upon completion of each thumbnail read
* operation.
*
* @param source the <code>ImageReader</code> object calling this
* method.
*/
void thumbnailComplete(ImageReader source);
/** {@collect.stats}
* Reports that a read has been aborted via the reader's
* <code>abort</code> method. No further notifications will be
* given.
*
* @param source the <code>ImageReader</code> object calling this
* method.
*/
void readAborted(ImageReader source);
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.event;
import java.util.EventListener;
import javax.imageio.ImageWriter;
/** {@collect.stats}
* An interface used by <code>ImageWriter</code> implementations to
* notify callers of their image and thumbnail reading methods of
* warnings (non-fatal errors). Fatal errors cause the relevant
* read method to throw an <code>IIOException</code>.
*
* <p> Localization is handled by associating a <code>Locale</code>
* with each <code>IIOWriteWarningListener</code> as it is registered
* with an <code>ImageWriter</code>. It is up to the
* <code>ImageWriter</code> to provide localized messages.
*
* @see javax.imageio.ImageWriter#addIIOWriteWarningListener
* @see javax.imageio.ImageWriter#removeIIOWriteWarningListener
*
*/
public interface IIOWriteWarningListener extends EventListener {
/** {@collect.stats}
* Reports the occurence of a non-fatal error in encoding. Encoding
* will continue following the call to this method. The application
* may choose to display a dialog, print the warning to the console,
* ignore the warning, or take any other action it chooses.
*
* @param source the <code>ImageWriter</code> object calling this method.
* @param imageIndex the index, starting with 0, of the image
* generating the warning.
* @param warning a <code>String</code> containing the warning.
*/
void warningOccurred(ImageWriter source,
int imageIndex,
String warning);
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.event;
import java.util.EventListener;
import javax.imageio.ImageWriter;
/** {@collect.stats}
* An interface used by <code>ImageWriter</code> implementations to notify
* callers of their image writing methods of progress.
*
* @see javax.imageio.ImageWriter#write
*
*/
public interface IIOWriteProgressListener extends EventListener {
/** {@collect.stats}
* Reports that an image write operation is beginning. All
* <code>ImageWriter</code> implementations are required to call
* this method exactly once when beginning an image write
* operation.
*
* @param source the <code>ImageWriter</code> object calling this
* method.
* @param imageIndex the index of the image being written within
* its containing input file or stream.
*/
void imageStarted(ImageWriter source, int imageIndex);
/** {@collect.stats}
* Reports the approximate degree of completion of the current
* <code>write</code> call within the associated
* <code>ImageWriter</code>.
*
* <p> The degree of completion is expressed as an index
* indicating which image is being written, and a percentage
* varying from <code>0.0F</code> to <code>100.0F</code>
* indicating how much of the current image has been output. The
* percentage should ideally be calculated in terms of the
* remaining time to completion, but it is usually more practical
* to use a more well-defined metric such as pixels decoded or
* portion of input stream consumed. In any case, a sequence of
* calls to this method during a given read operation should
* supply a monotonically increasing sequence of percentage
* values. It is not necessary to supply the exact values
* <code>0</code> and <code>100</code>, as these may be inferred
* by the callee from other methods.
*
* <p> Each particular <code>ImageWriter</code> implementation may
* call this method at whatever frequency it desires. A rule of
* thumb is to call it around each 5 percent mark.
*
* @param source the <code>ImageWriter</code> object calling this method.
* @param percentageDone the approximate percentage of decoding that
* has been completed.
*/
void imageProgress(ImageWriter source,
float percentageDone);
/** {@collect.stats}
* Reports that the image write operation has completed. All
* <code>ImageWriter</code> implementations are required to call
* this method exactly once upon completion of each image write
* operation.
*
* @param source the <code>ImageWriter</code> object calling this method.
*/
void imageComplete(ImageWriter source);
/** {@collect.stats}
* Reports that a thumbnail write operation is beginning. All
* <code>ImageWriter</code> implementations are required to call
* this method exactly once when beginning a thumbnail write
* operation.
*
* @param source the <code>ImageWrite</code> object calling this method.
* @param imageIndex the index of the image being written within its
* containing input file or stream.
* @param thumbnailIndex the index of the thumbnail being written.
*/
void thumbnailStarted(ImageWriter source,
int imageIndex, int thumbnailIndex);
/** {@collect.stats}
* Reports the approximate degree of completion of the current
* thumbnail write within the associated <code>ImageWriter</code>.
* The semantics are identical to those of
* <code>imageProgress</code>.
*
* @param source the <code>ImageWriter</code> object calling this
* method.
* @param percentageDone the approximate percentage of decoding that
* has been completed.
*/
void thumbnailProgress(ImageWriter source, float percentageDone);
/** {@collect.stats}
* Reports that a thumbnail write operation has completed. All
* <code>ImageWriter</code> implementations are required to call
* this method exactly once upon completion of each thumbnail
* write operation.
*
* @param source the <code>ImageWriter</code> object calling this
* method.
*/
void thumbnailComplete(ImageWriter source);
/** {@collect.stats}
* Reports that a write has been aborted via the writer's
* <code>abort</code> method. No further notifications will be
* given.
*
* @param source the <code>ImageWriter</code> object calling this
* method.
*/
void writeAborted(ImageWriter source);
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.event;
import java.awt.image.BufferedImage;
import java.util.EventListener;
import javax.imageio.ImageReader;
/** {@collect.stats}
* An interface used by <code>ImageReader</code> implementations to
* notify callers of their image and thumbnail reading methods of
* pixel updates.
*
* @see javax.imageio.ImageReader#addIIOReadUpdateListener
* @see javax.imageio.ImageReader#removeIIOReadUpdateListener
*
*/
public interface IIOReadUpdateListener extends EventListener {
/** {@collect.stats}
* Reports that the current read operation is about to begin a
* progressive pass. Readers of formats that support progressive
* encoding should use this to notify clients when each pass is
* completed when reading a progressively encoded image.
*
* <p> An estimate of the area that will be updated by the pass is
* indicated by the <code>minX</code>, <code>minY</code>,
* <code>width</code>, and <code>height</code> parameters. If the
* pass is interlaced, that is, it only updates selected rows or
* columns, the <code>periodX</code> and <code>periodY</code>
* parameters will indicate the degree of subsampling. The set of
* bands that may be affected is indicated by the value of
* <code>bands</code>.
*
* @param source the <code>ImageReader</code> object calling this
* method.
* @param theImage the <code>BufferedImage</code> being updated.
* @param pass the numer of the pass that is about to begin,
* starting with 0.
* @param minPass the index of the first pass that will be decoded.
* @param maxPass the index of the last pass that will be decoded.
* @param minX the X coordinate of the leftmost updated column
* of pixels.
* @param minY the Y coordinate of the uppermost updated row
* of pixels.
* @param periodX the horizontal spacing between updated pixels;
* a value of 1 means no gaps.
* @param periodY the vertical spacing between updated pixels;
* a value of 1 means no gaps.
* @param bands an array of <code>int</code>s indicating the the
* set bands that may be updated.
*/
void passStarted(ImageReader source,
BufferedImage theImage,
int pass,
int minPass, int maxPass,
int minX, int minY,
int periodX, int periodY,
int[] bands);
/** {@collect.stats}
* Reports that a given region of the image has been updated.
* The application might choose to redisplay the specified area,
* for example, in order to provide a progressive display effect,
* or perform other incremental processing.
*
* <p> Note that different image format readers may produce
* decoded pixels in a variety of different orders. Many readers
* will produce pixels in a simple top-to-bottom,
* left-to-right-order, but others may use multiple passes of
* interlacing, tiling, etc. The sequence of updates may even
* differ from call to call depending on network speeds, for
* example. A call to this method does not guarantee that all the
* specified pixels have actually been updated, only that some
* activity has taken place within some subregion of the one
* specified.
*
* <p> The particular <code>ImageReader</code> implementation may
* choose how often to provide updates. Each update specifies
* that a given region of the image has been updated since the
* last update. A region is described by its spatial bounding box
* (<code>minX</code>, <code>minY</code>, <code>width</code>, and
* <code>height</code>); X and Y subsampling factors
* (<code>periodX</code> and <code>periodY</code>); and a set of
* updated bands (<code>bands</code>). For example, the update:
*
* <pre>
* minX = 10
* minY = 20
* width = 3
* height = 4
* periodX = 2
* periodY = 3
* bands = { 1, 3 }
* </pre>
*
* would indicate that bands 1 and 3 of the following pixels were
* updated:
*
* <pre>
* (10, 20) (12, 20) (14, 20)
* (10, 23) (12, 23) (14, 23)
* (10, 26) (12, 26) (14, 26)
* (10, 29) (12, 29) (14, 29)
* </pre>
*
* @param source the <code>ImageReader</code> object calling this method.
* @param theImage the <code>BufferedImage</code> being updated.
* @param minX the X coordinate of the leftmost updated column
* of pixels.
* @param minY the Y coordinate of the uppermost updated row
* of pixels.
* @param width the number of updated pixels horizontally.
* @param height the number of updated pixels vertically.
* @param periodX the horizontal spacing between updated pixels;
* a value of 1 means no gaps.
* @param periodY the vertical spacing between updated pixels;
* a value of 1 means no gaps.
* @param bands an array of <code>int</code>s indicating which
* bands are being updated.
*/
void imageUpdate(ImageReader source,
BufferedImage theImage,
int minX, int minY,
int width, int height,
int periodX, int periodY,
int[] bands);
/** {@collect.stats}
* Reports that the current read operation has completed a
* progressive pass. Readers of formats that support
* progressive encoding should use this to notify clients when
* each pass is completed when reading a progressively
* encoded image.
*
* @param source the <code>ImageReader</code> object calling this
* method.
* @param theImage the <code>BufferedImage</code> being updated.
*
* @see javax.imageio.ImageReadParam#setSourceProgressivePasses(int, int)
*/
void passComplete(ImageReader source, BufferedImage theImage);
/** {@collect.stats}
* Reports that the current thumbnail read operation is about to
* begin a progressive pass. Readers of formats that support
* progressive encoding should use this to notify clients when
* each pass is completed when reading a progressively encoded
* thumbnail image.
*
* @param source the <code>ImageReader</code> object calling this
* method.
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
* @param pass the numer of the pass that is about to begin,
* starting with 0.
* @param minPass the index of the first pass that will be decoded.
* @param maxPass the index of the last pass that will be decoded.
* @param minX the X coordinate of the leftmost updated column
* of pixels.
* @param minY the Y coordinate of the uppermost updated row
* of pixels.
* @param periodX the horizontal spacing between updated pixels;
* a value of 1 means no gaps.
* @param periodY the vertical spacing between updated pixels;
* a value of 1 means no gaps.
* @param bands an array of <code>int</code>s indicating the the
* set bands that may be updated.
*
* @see #passStarted
*/
void thumbnailPassStarted(ImageReader source,
BufferedImage theThumbnail,
int pass,
int minPass, int maxPass,
int minX, int minY,
int periodX, int periodY,
int[] bands);
/** {@collect.stats}
* Reports that a given region of a thumbnail image has been updated.
* The application might choose to redisplay the specified area,
* for example, in order to provide a progressive display effect,
* or perform other incremental processing.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
* @param minX the X coordinate of the leftmost updated column
* of pixels.
* @param minY the Y coordinate of the uppermost updated row
* of pixels.
* @param width the number of updated pixels horizontally.
* @param height the number of updated pixels vertically.
* @param periodX the horizontal spacing between updated pixels;
* a value of 1 means no gaps.
* @param periodY the vertical spacing between updated pixels;
* a value of 1 means no gaps.
* @param bands an array of <code>int</code>s indicating which
* bands are being updated.
*
* @see #imageUpdate
*/
void thumbnailUpdate(ImageReader source,
BufferedImage theThumbnail,
int minX, int minY,
int width, int height,
int periodX, int periodY,
int[] bands);
/** {@collect.stats}
* Reports that the current thumbnail read operation has completed
* a progressive pass. Readers of formats that support
* progressive encoding should use this to notify clients when
* each pass is completed when reading a progressively encoded
* thumbnail image.
*
* @param source the <code>ImageReader</code> object calling this
* method.
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
*
* @see #passComplete
*/
void thumbnailPassComplete(ImageReader source, BufferedImage theThumbnail);
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.event;
import java.util.EventListener;
import javax.imageio.ImageReader;
/** {@collect.stats}
* An interface used by <code>ImageReader</code> implementations to
* notify callers of their image and thumbnail reading methods of
* warnings (non-fatal errors). Fatal errors cause the relevant
* read method to throw an <code>IIOException</code>.
*
* <p> Localization is handled by associating a <code>Locale</code>
* with each <code>IIOReadWarningListener</code> as it is registered
* with an <code>ImageReader</code>. It is up to the
* <code>ImageReader</code> to provide localized messages.
*
* @see javax.imageio.ImageReader#addIIOReadWarningListener
* @see javax.imageio.ImageReader#removeIIOReadWarningListener
*
*/
public interface IIOReadWarningListener extends EventListener {
/** {@collect.stats}
* Reports the occurence of a non-fatal error in decoding. Decoding
* will continue following the call to this method. The application
* may choose to display a dialog, print the warning to the console,
* ignore the warning, or take any other action it chooses.
*
* @param source the <code>ImageReader</code> object calling this method.
* @param warning a <code>String</code> containing the warning.
*/
void warningOccurred(ImageReader source, String warning);
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.event.IIOReadWarningListener;
import javax.imageio.event.IIOReadProgressListener;
import javax.imageio.event.IIOReadUpdateListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.stream.ImageInputStream;
/** {@collect.stats}
* An abstract superclass for parsing and decoding of images. This
* class must be subclassed by classes that read in images in the
* context of the Java Image I/O framework.
*
* <p> <code>ImageReader</code> objects are normally instantiated by
* the service provider interface (SPI) class for the specific format.
* Service provider classes (e.g., instances of
* <code>ImageReaderSpi</code>) are registered with the
* <code>IIORegistry</code>, which uses them for format recognition
* and presentation of available format readers and writers.
*
* <p> When an input source is set (using the <code>setInput</code>
* method), it may be marked as "seek forward only". This setting
* means that images contained within the input source will only be
* read in order, possibly allowing the reader to avoid caching
* portions of the input containing data associated with images that
* have been read previously.
*
* @see ImageWriter
* @see javax.imageio.spi.IIORegistry
* @see javax.imageio.spi.ImageReaderSpi
*
*/
public abstract class ImageReader {
/** {@collect.stats}
* The <code>ImageReaderSpi</code> that instantiated this object,
* or <code>null</code> if its identity is not known or none
* exists. By default it is initialized to <code>null</code>.
*/
protected ImageReaderSpi originatingProvider;
/** {@collect.stats}
* The <code>ImageInputStream</code> or other
* <code>Object</code> by <code>setInput</code> and retrieved
* by <code>getInput</code>. By default it is initialized to
* <code>null</code>.
*/
protected Object input = null;
/** {@collect.stats}
* <code>true</code> if the current input source has been marked
* as allowing only forward seeking by <code>setInput</code>. By
* default, the value is <code>false</code>.
*
* @see #minIndex
* @see #setInput
*/
protected boolean seekForwardOnly = false;
/** {@collect.stats}
* <code>true</code> if the current input source has been marked
* as allowing metadata to be ignored by <code>setInput</code>.
* By default, the value is <code>false</code>.
*
* @see #setInput
*/
protected boolean ignoreMetadata = false;
/** {@collect.stats}
* The smallest valid index for reading, initially 0. When
* <code>seekForwardOnly</code> is <code>true</code>, various methods
* may throw an <code>IndexOutOfBoundsException</code> on an
* attempt to access data associate with an image having a lower
* index.
*
* @see #seekForwardOnly
* @see #setInput
*/
protected int minIndex = 0;
/** {@collect.stats}
* An array of <code>Locale</code>s which may be used to localize
* warning messages, or <code>null</code> if localization is not
* supported.
*/
protected Locale[] availableLocales = null;
/** {@collect.stats}
* The current <code>Locale</code> to be used for localization, or
* <code>null</code> if none has been set.
*/
protected Locale locale = null;
/** {@collect.stats}
* A <code>List</code> of currently registered
* <code>IIOReadWarningListener</code>s, initialized by default to
* <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<IIOReadWarningListener> warningListeners = null;
/** {@collect.stats}
* A <code>List</code> of the <code>Locale</code>s associated with
* each currently registered <code>IIOReadWarningListener</code>,
* initialized by default to <code>null</code>, which is
* synonymous with an empty <code>List</code>.
*/
protected List<Locale> warningLocales = null;
/** {@collect.stats}
* A <code>List</code> of currently registered
* <code>IIOReadProgressListener</code>s, initialized by default
* to <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<IIOReadProgressListener> progressListeners = null;
/** {@collect.stats}
* A <code>List</code> of currently registered
* <code>IIOReadUpdateListener</code>s, initialized by default to
* <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<IIOReadUpdateListener> updateListeners = null;
/** {@collect.stats}
* If <code>true</code>, the current read operation should be
* aborted.
*/
private boolean abortFlag = false;
/** {@collect.stats}
* Constructs an <code>ImageReader</code> and sets its
* <code>originatingProvider</code> field to the supplied value.
*
* <p> Subclasses that make use of extensions should provide a
* constructor with signature <code>(ImageReaderSpi,
* Object)</code> in order to retrieve the extension object. If
* the extension object is unsuitable, an
* <code>IllegalArgumentException</code> should be thrown.
*
* @param originatingProvider the <code>ImageReaderSpi</code> that is
* invoking this constructor, or <code>null</code>.
*/
protected ImageReader(ImageReaderSpi originatingProvider) {
this.originatingProvider = originatingProvider;
}
/** {@collect.stats}
* Returns a <code>String</code> identifying the format of the
* input source.
*
* <p> The default implementation returns
* <code>originatingProvider.getFormatNames()[0]</code>.
* Implementations that may not have an originating service
* provider, or which desire a different naming policy should
* override this method.
*
* @exception IOException if an error occurs reading the
* information from the input source.
*
* @return the format name, as a <code>String</code>.
*/
public String getFormatName() throws IOException {
return originatingProvider.getFormatNames()[0];
}
/** {@collect.stats}
* Returns the <code>ImageReaderSpi</code> that was passed in on
* the constructor. Note that this value may be <code>null</code>.
*
* @return an <code>ImageReaderSpi</code>, or <code>null</code>.
*
* @see ImageReaderSpi
*/
public ImageReaderSpi getOriginatingProvider() {
return originatingProvider;
}
/** {@collect.stats}
* Sets the input source to use to the given
* <code>ImageInputStream</code> or other <code>Object</code>.
* The input source must be set before any of the query or read
* methods are used. If <code>input</code> is <code>null</code>,
* any currently set input source will be removed. In any case,
* the value of <code>minIndex</code> will be initialized to 0.
*
* <p> The <code>seekForwardOnly</code> parameter controls whether
* the value returned by <code>getMinIndex</code> will be
* increased as each image (or thumbnail, or image metadata) is
* read. If <code>seekForwardOnly</code> is true, then a call to
* <code>read(index)</code> will throw an
* <code>IndexOutOfBoundsException</code> if <code>index <
* this.minIndex</code>; otherwise, the value of
* <code>minIndex</code> will be set to <code>index</code>. If
* <code>seekForwardOnly</code> is <code>false</code>, the value of
* <code>minIndex</code> will remain 0 regardless of any read
* operations.
*
* <p> The <code>ignoreMetadata</code> parameter, if set to
* <code>true</code>, allows the reader to disregard any metadata
* encountered during the read. Subsequent calls to the
* <code>getStreamMetadata</code> and
* <code>getImageMetadata</code> methods may return
* <code>null</code>, and an <code>IIOImage</code> returned from
* <code>readAll</code> may return <code>null</code> from their
* <code>getMetadata</code> method. Setting this parameter may
* allow the reader to work more efficiently. The reader may
* choose to disregard this setting and return metadata normally.
*
* <p> Subclasses should take care to remove any cached
* information based on the previous stream, such as header
* information or partially decoded image data.
*
* <p> Use of a general <code>Object</code> other than an
* <code>ImageInputStream</code> is intended for readers that
* interact directly with a capture device or imaging protocol.
* The set of legal classes is advertised by the reader's service
* provider's <code>getInputTypes</code> method; most readers
* will return a single-element array containing only
* <code>ImageInputStream.class</code> to indicate that they
* accept only an <code>ImageInputStream</code>.
*
* <p> The default implementation checks the <code>input</code>
* argument against the list returned by
* <code>originatingProvider.getInputTypes()</code> and fails
* if the argument is not an instance of one of the classes
* in the list. If the originating provider is set to
* <code>null</code>, the input is accepted only if it is an
* <code>ImageInputStream</code>.
*
* @param input the <code>ImageInputStream</code> or other
* <code>Object</code> to use for future decoding.
* @param seekForwardOnly if <code>true</code>, images and metadata
* may only be read in ascending order from this input source.
* @param ignoreMetadata if <code>true</code>, metadata
* may be ignored during reads.
*
* @exception IllegalArgumentException if <code>input</code> is
* not an instance of one of the classes returned by the
* originating service provider's <code>getInputTypes</code>
* method, or is not an <code>ImageInputStream</code>.
*
* @see ImageInputStream
* @see #getInput
* @see javax.imageio.spi.ImageReaderSpi#getInputTypes
*/
public void setInput(Object input,
boolean seekForwardOnly,
boolean ignoreMetadata) {
if (input != null) {
boolean found = false;
if (originatingProvider != null) {
Class[] classes = originatingProvider.getInputTypes();
for (int i = 0; i < classes.length; i++) {
if (classes[i].isInstance(input)) {
found = true;
break;
}
}
} else {
if (input instanceof ImageInputStream) {
found = true;
}
}
if (!found) {
throw new IllegalArgumentException("Incorrect input type!");
}
this.seekForwardOnly = seekForwardOnly;
this.ignoreMetadata = ignoreMetadata;
this.minIndex = 0;
}
this.input = input;
}
/** {@collect.stats}
* Sets the input source to use to the given
* <code>ImageInputStream</code> or other <code>Object</code>.
* The input source must be set before any of the query or read
* methods are used. If <code>input</code> is <code>null</code>,
* any currently set input source will be removed. In any case,
* the value of <code>minIndex</code> will be initialized to 0.
*
* <p> The <code>seekForwardOnly</code> parameter controls whether
* the value returned by <code>getMinIndex</code> will be
* increased as each image (or thumbnail, or image metadata) is
* read. If <code>seekForwardOnly</code> is true, then a call to
* <code>read(index)</code> will throw an
* <code>IndexOutOfBoundsException</code> if <code>index <
* this.minIndex</code>; otherwise, the value of
* <code>minIndex</code> will be set to <code>index</code>. If
* <code>seekForwardOnly</code> is <code>false</code>, the value of
* <code>minIndex</code> will remain 0 regardless of any read
* operations.
*
* <p> This method is equivalent to <code>setInput(input,
* seekForwardOnly, false)</code>.
*
* @param input the <code>ImageInputStream</code> or other
* <code>Object</code> to use for future decoding.
* @param seekForwardOnly if <code>true</code>, images and metadata
* may only be read in ascending order from this input source.
*
* @exception IllegalArgumentException if <code>input</code> is
* not an instance of one of the classes returned by the
* originating service provider's <code>getInputTypes</code>
* method, or is not an <code>ImageInputStream</code>.
*
* @see #getInput
*/
public void setInput(Object input,
boolean seekForwardOnly) {
setInput(input, seekForwardOnly, false);
}
/** {@collect.stats}
* Sets the input source to use to the given
* <code>ImageInputStream</code> or other <code>Object</code>.
* The input source must be set before any of the query or read
* methods are used. If <code>input</code> is <code>null</code>,
* any currently set input source will be removed. In any case,
* the value of <code>minIndex</code> will be initialized to 0.
*
* <p> This method is equivalent to <code>setInput(input, false,
* false)</code>.
*
* @param input the <code>ImageInputStream</code> or other
* <code>Object</code> to use for future decoding.
*
* @exception IllegalArgumentException if <code>input</code> is
* not an instance of one of the classes returned by the
* originating service provider's <code>getInputTypes</code>
* method, or is not an <code>ImageInputStream</code>.
*
* @see #getInput
*/
public void setInput(Object input) {
setInput(input, false, false);
}
/** {@collect.stats}
* Returns the <code>ImageInputStream</code> or other
* <code>Object</code> previously set as the input source. If the
* input source has not been set, <code>null</code> is returned.
*
* @return the <code>Object</code> that will be used for future
* decoding, or <code>null</code>.
*
* @see ImageInputStream
* @see #setInput
*/
public Object getInput() {
return input;
}
/** {@collect.stats}
* Returns <code>true</code> if the current input source has been
* marked as seek forward only by passing <code>true</code> as the
* <code>seekForwardOnly</code> argument to the
* <code>setInput</code> method.
*
* @return <code>true</code> if the input source is seek forward
* only.
*
* @see #setInput
*/
public boolean isSeekForwardOnly() {
return seekForwardOnly;
}
/** {@collect.stats}
* Returns <code>true</code> if the current input source has been
* marked as allowing metadata to be ignored by passing
* <code>true</code> as the <code>ignoreMetadata</code> argument
* to the <code>setInput</code> method.
*
* @return <code>true</code> if the metadata may be ignored.
*
* @see #setInput
*/
public boolean isIgnoringMetadata() {
return ignoreMetadata;
}
/** {@collect.stats}
* Returns the lowest valid index for reading an image, thumbnail,
* or image metadata. If <code>seekForwardOnly()</code> is
* <code>false</code>, this value will typically remain 0,
* indicating that random access is possible. Otherwise, it will
* contain the value of the most recently accessed index, and
* increase in a monotonic fashion.
*
* @return the minimum legal index for reading.
*/
public int getMinIndex() {
return minIndex;
}
// Localization
/** {@collect.stats}
* Returns an array of <code>Locale</code>s that may be used to
* localize warning listeners and compression settings. A return
* value of <code>null</code> indicates that localization is not
* supported.
*
* <p> The default implementation returns a clone of the
* <code>availableLocales</code> instance variable if it is
* non-<code>null</code>, or else returns <code>null</code>.
*
* @return an array of <code>Locale</code>s that may be used as
* arguments to <code>setLocale</code>, or <code>null</code>.
*/
public Locale[] getAvailableLocales() {
if (availableLocales == null) {
return null;
} else {
return (Locale[])availableLocales.clone();
}
}
/** {@collect.stats}
* Sets the current <code>Locale</code> of this
* <code>ImageReader</code> to the given value. A value of
* <code>null</code> removes any previous setting, and indicates
* that the reader should localize as it sees fit.
*
* @param locale the desired <code>Locale</code>, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>locale</code> is
* non-<code>null</code> but is not one of the values returned by
* <code>getAvailableLocales</code>.
*
* @see #getLocale
*/
public void setLocale(Locale locale) {
if (locale != null) {
Locale[] locales = getAvailableLocales();
boolean found = false;
if (locales != null) {
for (int i = 0; i < locales.length; i++) {
if (locale.equals(locales[i])) {
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("Invalid locale!");
}
}
this.locale = locale;
}
/** {@collect.stats}
* Returns the currently set <code>Locale</code>, or
* <code>null</code> if none has been set.
*
* @return the current <code>Locale</code>, or <code>null</code>.
*
* @see #setLocale
*/
public Locale getLocale() {
return locale;
}
// Image queries
/** {@collect.stats}
* Returns the number of images, not including thumbnails, available
* from the current input source.
*
* <p> Note that some image formats (such as animated GIF) do not
* specify how many images are present in the stream. Thus
* determining the number of images will require the entire stream
* to be scanned and may require memory for buffering. If images
* are to be processed in order, it may be more efficient to
* simply call <code>read</code> with increasing indices until an
* <code>IndexOutOfBoundsException</code> is thrown to indicate
* that no more images are available. The
* <code>allowSearch</code> parameter may be set to
* <code>false</code> to indicate that an exhaustive search is not
* desired; the return value will be <code>-1</code> to indicate
* that a search is necessary. If the input has been specified
* with <code>seekForwardOnly</code> set to <code>true</code>,
* this method throws an <code>IllegalStateException</code> if
* <code>allowSearch</code> is set to <code>true</code>.
*
* @param allowSearch if <code>true</code>, the true number of
* images will be returned even if a search is required. If
* <code>false</code>, the reader may return <code>-1</code>
* without performing the search.
*
* @return the number of images, as an <code>int</code>, or
* <code>-1</code> if <code>allowSearch</code> is
* <code>false</code> and a search would be required.
*
* @exception IllegalStateException if the input source has not been set,
* or if the input has been specified with <code>seekForwardOnly</code>
* set to <code>true</code>.
* @exception IOException if an error occurs reading the
* information from the input source.
*
* @see #setInput
*/
public abstract int getNumImages(boolean allowSearch) throws IOException;
/** {@collect.stats}
* Returns the width in pixels of the given image within the input
* source.
*
* <p> If the image can be rendered to a user-specified size, then
* this method returns the default width.
*
* @param imageIndex the index of the image to be queried.
*
* @return the width of the image, as an <code>int</code>.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs reading the width
* information from the input source.
*/
public abstract int getWidth(int imageIndex) throws IOException;
/** {@collect.stats}
* Returns the height in pixels of the given image within the
* input source.
*
* <p> If the image can be rendered to a user-specified size, then
* this method returns the default height.
*
* @param imageIndex the index of the image to be queried.
*
* @return the height of the image, as an <code>int</code>.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs reading the height
* information from the input source.
*/
public abstract int getHeight(int imageIndex) throws IOException;
/** {@collect.stats}
* Returns <code>true</code> if the storage format of the given
* image places no inherent impediment on random access to pixels.
* For most compressed formats, such as JPEG, this method should
* return <code>false</code>, as a large section of the image in
* addition to the region of interest may need to be decoded.
*
* <p> This is merely a hint for programs that wish to be
* efficient; all readers must be able to read arbitrary regions
* as specified in an <code>ImageReadParam</code>.
*
* <p> Note that formats that return <code>false</code> from
* this method may nonetheless allow tiling (<i>e.g.</i> Restart
* Markers in JPEG), and random access will likely be reasonably
* efficient on tiles. See {@link #isImageTiled
* <code>isImageTiled</code>}.
*
* <p> A reader for which all images are guaranteed to support
* easy random access, or are guaranteed not to support easy
* random access, may return <code>true</code> or
* <code>false</code> respectively without accessing any image
* data. In such cases, it is not necessary to throw an exception
* even if no input source has been set or the image index is out
* of bounds.
*
* <p> The default implementation returns <code>false</code>.
*
* @param imageIndex the index of the image to be queried.
*
* @return <code>true</code> if reading a region of interest of
* the given image is likely to be efficient.
*
* @exception IllegalStateException if an input source is required
* to determine the return value, but none has been set.
* @exception IndexOutOfBoundsException if an image must be
* accessed to determine the return value, but the supplied index
* is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public boolean isRandomAccessEasy(int imageIndex) throws IOException {
return false;
}
/** {@collect.stats}
* Returns the aspect ratio of the given image (that is, its width
* divided by its height) as a <code>float</code>. For images
* that are inherently resizable, this method provides a way to
* determine the appropriate width given a deired height, or vice
* versa. For non-resizable images, the true width and height
* are used.
*
* <p> The default implementation simply returns
* <code>(float)getWidth(imageIndex)/getHeight(imageIndex)</code>.
*
* @param imageIndex the index of the image to be queried.
*
* @return a <code>float</code> indicating the aspect ratio of the
* given image.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public float getAspectRatio(int imageIndex) throws IOException {
return (float)getWidth(imageIndex)/getHeight(imageIndex);
}
/** {@collect.stats}
* Returns an <code>ImageTypeSpecifier</code> indicating the
* <code>SampleModel</code> and <code>ColorModel</code> which most
* closely represents the "raw" internal format of the image. For
* example, for a JPEG image the raw type might have a YCbCr color
* space even though the image would conventionally be transformed
* into an RGB color space prior to display. The returned value
* should also be included in the list of values returned by
* <code>getImageTypes</code>.
*
* <p> The default implementation simply returns the first entry
* from the list provided by <code>getImageType</code>.
*
* @param imageIndex the index of the image to be queried.
*
* @return an <code>ImageTypeSpecifier</code>.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs reading the format
* information from the input source.
*/
public ImageTypeSpecifier getRawImageType(int imageIndex)
throws IOException {
return (ImageTypeSpecifier)getImageTypes(imageIndex).next();
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing possible image
* types to which the given image may be decoded, in the form of
* <code>ImageTypeSpecifiers</code>s. At least one legal image
* type will be returned.
*
* <p> The first element of the iterator should be the most
* "natural" type for decoding the image with as little loss as
* possible. For example, for a JPEG image the first entry should
* be an RGB image, even though the image data is stored
* internally in a YCbCr color space.
*
* @param imageIndex the index of the image to be
* <code>retrieved</code>.
*
* @return an <code>Iterator</code> containing at least one
* <code>ImageTypeSpecifier</code> representing suggested image
* types for decoding the current given image.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs reading the format
* information from the input source.
*
* @see ImageReadParam#setDestination(BufferedImage)
* @see ImageReadParam#setDestinationType(ImageTypeSpecifier)
*/
public abstract Iterator<ImageTypeSpecifier>
getImageTypes(int imageIndex) throws IOException;
/** {@collect.stats}
* Returns a default <code>ImageReadParam</code> object
* appropriate for this format. All subclasses should define a
* set of default values for all parameters and return them with
* this call. This method may be called before the input source
* is set.
*
* <p> The default implementation constructs and returns a new
* <code>ImageReadParam</code> object that does not allow source
* scaling (<i>i.e.</i>, it returns <code>new
* ImageReadParam()</code>.
*
* @return an <code>ImageReadParam</code> object which may be used
* to control the decoding process using a set of default settings.
*/
public ImageReadParam getDefaultReadParam() {
return new ImageReadParam();
}
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object representing the
* metadata associated with the input source as a whole (i.e., not
* associated with any particular image), or <code>null</code> if
* the reader does not support reading metadata, is set to ignore
* metadata, or if no metadata is available.
*
* @return an <code>IIOMetadata</code> object, or <code>null</code>.
*
* @exception IOException if an error occurs during reading.
*/
public abstract IIOMetadata getStreamMetadata() throws IOException;
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object representing the
* metadata associated with the input source as a whole (i.e.,
* not associated with any particular image). If no such data
* exists, <code>null</code> is returned.
*
* <p> The resuting metadata object is only responsible for
* returning documents in the format named by
* <code>formatName</code>. Within any documents that are
* returned, only nodes whose names are members of
* <code>nodeNames</code> are required to be returned. In this
* way, the amount of metadata processing done by the reader may
* be kept to a minimum, based on what information is actually
* needed.
*
* <p> If <code>formatName</code> is not the name of a supported
* metadata format, <code>null</code> is returned.
*
* <p> In all cases, it is legal to return a more capable metadata
* object than strictly necessary. The format name and node names
* are merely hints that may be used to reduce the reader's
* workload.
*
* <p> The default implementation simply returns the result of
* calling <code>getStreamMetadata()</code>, after checking that
* the format name is supported. If it is not,
* <code>null</code> is returned.
*
* @param formatName a metadata format name that may be used to retrieve
* a document from the returned <code>IIOMetadata</code> object.
* @param nodeNames a <code>Set</code> containing the names of
* nodes that may be contained in a retrieved document.
*
* @return an <code>IIOMetadata</code> object, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>nodeNames</code>
* is <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public IIOMetadata getStreamMetadata(String formatName,
Set<String> nodeNames)
throws IOException
{
return getMetadata(formatName, nodeNames, true, 0);
}
private IIOMetadata getMetadata(String formatName,
Set nodeNames,
boolean wantStream,
int imageIndex) throws IOException {
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
if (nodeNames == null) {
throw new IllegalArgumentException("nodeNames == null!");
}
IIOMetadata metadata =
wantStream
? getStreamMetadata()
: getImageMetadata(imageIndex);
if (metadata != null) {
if (metadata.isStandardMetadataFormatSupported() &&
formatName.equals
(IIOMetadataFormatImpl.standardMetadataFormatName)) {
return metadata;
}
String nativeName = metadata.getNativeMetadataFormatName();
if (nativeName != null && formatName.equals(nativeName)) {
return metadata;
}
String[] extraNames = metadata.getExtraMetadataFormatNames();
if (extraNames != null) {
for (int i = 0; i < extraNames.length; i++) {
if (formatName.equals(extraNames[i])) {
return metadata;
}
}
}
}
return null;
}
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object containing metadata
* associated with the given image, or <code>null</code> if the
* reader does not support reading metadata, is set to ignore
* metadata, or if no metadata is available.
*
* @param imageIndex the index of the image whose metadata is to
* be retrieved.
*
* @return an <code>IIOMetadata</code> object, or
* <code>null</code>.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public abstract IIOMetadata getImageMetadata(int imageIndex)
throws IOException;
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object representing the
* metadata associated with the given image, or <code>null</code>
* if the reader does not support reading metadata or none
* is available.
*
* <p> The resuting metadata object is only responsible for
* returning documents in the format named by
* <code>formatName</code>. Within any documents that are
* returned, only nodes whose names are members of
* <code>nodeNames</code> are required to be returned. In this
* way, the amount of metadata processing done by the reader may
* be kept to a minimum, based on what information is actually
* needed.
*
* <p> If <code>formatName</code> is not the name of a supported
* metadata format, <code>null</code> may be returned.
*
* <p> In all cases, it is legal to return a more capable metadata
* object than strictly necessary. The format name and node names
* are merely hints that may be used to reduce the reader's
* workload.
*
* <p> The default implementation simply returns the result of
* calling <code>getImageMetadata(imageIndex)</code>, after
* checking that the format name is supported. If it is not,
* <code>null</code> is returned.
*
* @param imageIndex the index of the image whose metadata is to
* be retrieved.
* @param formatName a metadata format name that may be used to retrieve
* a document from the returned <code>IIOMetadata</code> object.
* @param nodeNames a <code>Set</code> containing the names of
* nodes that may be contained in a retrieved document.
*
* @return an <code>IIOMetadata</code> object, or <code>null</code>.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>nodeNames</code>
* is <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public IIOMetadata getImageMetadata(int imageIndex,
String formatName,
Set<String> nodeNames)
throws IOException {
return getMetadata(formatName, nodeNames, false, imageIndex);
}
/** {@collect.stats}
* Reads the image indexed by <code>imageIndex</code> and returns
* it as a complete <code>BufferedImage</code>, using a default
* <code>ImageReadParam</code>. This is a convenience method
* that calls <code>read(imageIndex, null)</code>.
*
* <p> The image returned will be formatted according to the first
* <code>ImageTypeSpecifier</code> returned from
* <code>getImageTypes</code>.
*
* <p> Any registered <code>IIOReadProgressListener</code> objects
* will be notified by calling their <code>imageStarted</code>
* method, followed by calls to their <code>imageProgress</code>
* method as the read progresses. Finally their
* <code>imageComplete</code> method will be called.
* <code>IIOReadUpdateListener</code> objects may be updated at
* other times during the read as pixels are decoded. Finally,
* <code>IIOReadWarningListener</code> objects will receive
* notification of any non-fatal warnings that occur during
* decoding.
*
* @param imageIndex the index of the image to be retrieved.
*
* @return the desired portion of the image as a
* <code>BufferedImage</code>.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public BufferedImage read(int imageIndex) throws IOException {
return read(imageIndex, null);
}
/** {@collect.stats}
* Reads the image indexed by <code>imageIndex</code> and returns
* it as a complete <code>BufferedImage</code>, using a supplied
* <code>ImageReadParam</code>.
*
* <p> The actual <code>BufferedImage</code> returned will be
* chosen using the algorithm defined by the
* <code>getDestination</code> method.
*
* <p> Any registered <code>IIOReadProgressListener</code> objects
* will be notified by calling their <code>imageStarted</code>
* method, followed by calls to their <code>imageProgress</code>
* method as the read progresses. Finally their
* <code>imageComplete</code> method will be called.
* <code>IIOReadUpdateListener</code> objects may be updated at
* other times during the read as pixels are decoded. Finally,
* <code>IIOReadWarningListener</code> objects will receive
* notification of any non-fatal warnings that occur during
* decoding.
*
* <p> The set of source bands to be read and destination bands to
* be written is determined by calling <code>getSourceBands</code>
* and <code>getDestinationBands</code> on the supplied
* <code>ImageReadParam</code>. If the lengths of the arrays
* returned by these methods differ, the set of source bands
* contains an index larger that the largest available source
* index, or the set of destination bands contains an index larger
* than the largest legal destination index, an
* <code>IllegalArgumentException</code> is thrown.
*
* <p> If the supplied <code>ImageReadParam</code> contains
* optional setting values not supported by this reader (<i>e.g.</i>
* source render size or any format-specific settings), they will
* be ignored.
*
* @param imageIndex the index of the image to be retrieved.
* @param param an <code>ImageReadParam</code> used to control
* the reading process, or <code>null</code>.
*
* @return the desired portion of the image as a
* <code>BufferedImage</code>.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IllegalArgumentException if the set of source and
* destination bands specified by
* <code>param.getSourceBands</code> and
* <code>param.getDestinationBands</code> differ in length or
* include indices that are out of bounds.
* @exception IllegalArgumentException if the resulting image would
* have a width or height less than 1.
* @exception IOException if an error occurs during reading.
*/
public abstract BufferedImage read(int imageIndex, ImageReadParam param)
throws IOException;
/** {@collect.stats}
* Reads the image indexed by <code>imageIndex</code> and returns
* an <code>IIOImage</code> containing the image, thumbnails, and
* associated image metadata, using a supplied
* <code>ImageReadParam</code>.
*
* <p> The actual <code>BufferedImage</code> referenced by the
* returned <code>IIOImage</code> will be chosen using the
* algorithm defined by the <code>getDestination</code> method.
*
* <p> Any registered <code>IIOReadProgressListener</code> objects
* will be notified by calling their <code>imageStarted</code>
* method, followed by calls to their <code>imageProgress</code>
* method as the read progresses. Finally their
* <code>imageComplete</code> method will be called.
* <code>IIOReadUpdateListener</code> objects may be updated at
* other times during the read as pixels are decoded. Finally,
* <code>IIOReadWarningListener</code> objects will receive
* notification of any non-fatal warnings that occur during
* decoding.
*
* <p> The set of source bands to be read and destination bands to
* be written is determined by calling <code>getSourceBands</code>
* and <code>getDestinationBands</code> on the supplied
* <code>ImageReadParam</code>. If the lengths of the arrays
* returned by these methods differ, the set of source bands
* contains an index larger that the largest available source
* index, or the set of destination bands contains an index larger
* than the largest legal destination index, an
* <code>IllegalArgumentException</code> is thrown.
*
* <p> Thumbnails will be returned in their entirety regardless of
* the region settings.
*
* <p> If the supplied <code>ImageReadParam</code> contains
* optional setting values not supported by this reader (<i>e.g.</i>
* source render size or any format-specific settings), those
* values will be ignored.
*
* @param imageIndex the index of the image to be retrieved.
* @param param an <code>ImageReadParam</code> used to control
* the reading process, or <code>null</code>.
*
* @return an <code>IIOImage</code> containing the desired portion
* of the image, a set of thumbnails, and associated image
* metadata.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IllegalArgumentException if the set of source and
* destination bands specified by
* <code>param.getSourceBands</code> and
* <code>param.getDestinationBands</code> differ in length or
* include indices that are out of bounds.
* @exception IllegalArgumentException if the resulting image
* would have a width or height less than 1.
* @exception IOException if an error occurs during reading.
*/
public IIOImage readAll(int imageIndex, ImageReadParam param)
throws IOException {
if (imageIndex < getMinIndex()) {
throw new IndexOutOfBoundsException("imageIndex < getMinIndex()!");
}
BufferedImage im = read(imageIndex, param);
ArrayList thumbnails = null;
int numThumbnails = getNumThumbnails(imageIndex);
if (numThumbnails > 0) {
thumbnails = new ArrayList();
for (int j = 0; j < numThumbnails; j++) {
thumbnails.add(readThumbnail(imageIndex, j));
}
}
IIOMetadata metadata = getImageMetadata(imageIndex);
return new IIOImage(im, thumbnails, metadata);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all the images,
* thumbnails, and metadata, starting at the index given by
* <code>getMinIndex</code>, from the input source in the form of
* <code>IIOImage</code> objects. An <code>Iterator</code>
* containing <code>ImageReadParam</code> objects is supplied; one
* element is consumed for each image read from the input source
* until no more images are available. If the read param
* <code>Iterator</code> runs out of elements, but there are still
* more images available from the input source, default read
* params are used for the remaining images.
*
* <p> If <code>params</code> is <code>null</code>, a default read
* param will be used for all images.
*
* <p> The actual <code>BufferedImage</code> referenced by the
* returned <code>IIOImage</code> will be chosen using the
* algorithm defined by the <code>getDestination</code> method.
*
* <p> Any registered <code>IIOReadProgressListener</code> objects
* will be notified by calling their <code>sequenceStarted</code>
* method once. Then, for each image decoded, there will be a
* call to <code>imageStarted</code>, followed by calls to
* <code>imageProgress</code> as the read progresses, and finally
* to <code>imageComplete</code>. The
* <code>sequenceComplete</code> method will be called after the
* last image has been decoded.
* <code>IIOReadUpdateListener</code> objects may be updated at
* other times during the read as pixels are decoded. Finally,
* <code>IIOReadWarningListener</code> objects will receive
* notification of any non-fatal warnings that occur during
* decoding.
*
* <p> The set of source bands to be read and destination bands to
* be written is determined by calling <code>getSourceBands</code>
* and <code>getDestinationBands</code> on the supplied
* <code>ImageReadParam</code>. If the lengths of the arrays
* returned by these methods differ, the set of source bands
* contains an index larger that the largest available source
* index, or the set of destination bands contains an index larger
* than the largest legal destination index, an
* <code>IllegalArgumentException</code> is thrown.
*
* <p> Thumbnails will be returned in their entirety regardless of the
* region settings.
*
* <p> If any of the supplied <code>ImageReadParam</code>s contain
* optional setting values not supported by this reader (<i>e.g.</i>
* source render size or any format-specific settings), they will
* be ignored.
*
* @param params an <code>Iterator</code> containing
* <code>ImageReadParam</code> objects.
*
* @return an <code>Iterator</code> representing the
* contents of the input source as <code>IIOImage</code>s.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IllegalArgumentException if any
* non-<code>null</code> element of <code>params</code> is not an
* <code>ImageReadParam</code>.
* @exception IllegalArgumentException if the set of source and
* destination bands specified by
* <code>param.getSourceBands</code> and
* <code>param.getDestinationBands</code> differ in length or
* include indices that are out of bounds.
* @exception IllegalArgumentException if a resulting image would
* have a width or height less than 1.
* @exception IOException if an error occurs during reading.
*
* @see ImageReadParam
* @see IIOImage
*/
public Iterator<IIOImage>
readAll(Iterator<? extends ImageReadParam> params)
throws IOException
{
List output = new ArrayList();
int imageIndex = getMinIndex();
// Inform IIOReadProgressListeners we're starting a sequence
processSequenceStarted(imageIndex);
while (true) {
// Inform IIOReadProgressListeners and IIOReadUpdateListeners
// that we're starting a new image
ImageReadParam param = null;
if (params != null && params.hasNext()) {
Object o = params.next();
if (o != null) {
if (o instanceof ImageReadParam) {
param = (ImageReadParam)o;
} else {
throw new IllegalArgumentException
("Non-ImageReadParam supplied as part of params!");
}
}
}
BufferedImage bi = null;
try {
bi = read(imageIndex, param);
} catch (IndexOutOfBoundsException e) {
break;
}
ArrayList thumbnails = null;
int numThumbnails = getNumThumbnails(imageIndex);
if (numThumbnails > 0) {
thumbnails = new ArrayList();
for (int j = 0; j < numThumbnails; j++) {
thumbnails.add(readThumbnail(imageIndex, j));
}
}
IIOMetadata metadata = getImageMetadata(imageIndex);
IIOImage im = new IIOImage(bi, thumbnails, metadata);
output.add(im);
++imageIndex;
}
// Inform IIOReadProgressListeners we're ending a sequence
processSequenceComplete();
return output.iterator();
}
/** {@collect.stats}
* Returns <code>true</code> if this plug-in supports reading
* just a {@link java.awt.image.Raster <code>Raster</code>} of pixel data.
* If this method returns <code>false</code>, calls to
* {@link #readRaster <code>readRaster</code>} or {@link #readTileRaster
* <code>readTileRaster</code>} will throw an
* <code>UnsupportedOperationException</code>.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if this plug-in supports reading raw
* <code>Raster</code>s.
*
* @see #readRaster
* @see #readTileRaster
*/
public boolean canReadRaster() {
return false;
}
/** {@collect.stats}
* Returns a new <code>Raster</code> object containing the raw pixel data
* from the image stream, without any color conversion applied. The
* application must determine how to interpret the pixel data by other
* means. Any destination or image-type parameters in the supplied
* <code>ImageReadParam</code> object are ignored, but all other
* parameters are used exactly as in the {@link #read <code>read</code>}
* method, except that any destination offset is used as a logical rather
* than a physical offset. The size of the returned <code>Raster</code>
* will always be that of the source region clipped to the actual image.
* Logical offsets in the stream itself are ignored.
*
* <p> This method allows formats that normally apply a color
* conversion, such as JPEG, and formats that do not normally have an
* associated colorspace, such as remote sensing or medical imaging data,
* to provide access to raw pixel data.
*
* <p> Any registered <code>readUpdateListener</code>s are ignored, as
* there is no <code>BufferedImage</code>, but all other listeners are
* called exactly as they are for the {@link #read <code>read</code>}
* method.
*
* <p> If {@link #canReadRaster <code>canReadRaster()</code>} returns
* <code>false</code>, this method throws an
* <code>UnsupportedOperationException</code>.
*
* <p> If the supplied <code>ImageReadParam</code> contains
* optional setting values not supported by this reader (<i>e.g.</i>
* source render size or any format-specific settings), they will
* be ignored.
*
* <p> The default implementation throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index of the image to be read.
* @param param an <code>ImageReadParam</code> used to control
* the reading process, or <code>null</code>.
*
* @return the desired portion of the image as a
* <code>Raster</code>.
*
* @exception UnsupportedOperationException if this plug-in does not
* support reading raw <code>Raster</code>s.
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*
* @see #canReadRaster
* @see #read
* @see java.awt.image.Raster
*/
public Raster readRaster(int imageIndex, ImageReadParam param)
throws IOException {
throw new UnsupportedOperationException("readRaster not supported!");
}
/** {@collect.stats}
* Returns <code>true</code> if the image is organized into
* <i>tiles</i>, that is, equal-sized non-overlapping rectangles.
*
* <p> A reader plug-in may choose whether or not to expose tiling
* that is present in the image as it is stored. It may even
* choose to advertise tiling when none is explicitly present. In
* general, tiling should only be advertised if there is some
* advantage (in speed or space) to accessing individual tiles.
* Regardless of whether the reader advertises tiling, it must be
* capable of reading an arbitrary rectangular region specified in
* an <code>ImageReadParam</code>.
*
* <p> A reader for which all images are guaranteed to be tiled,
* or are guaranteed not to be tiled, may return <code>true</code>
* or <code>false</code> respectively without accessing any image
* data. In such cases, it is not necessary to throw an exception
* even if no input source has been set or the image index is out
* of bounds.
*
* <p> The default implementation just returns <code>false</code>.
*
* @param imageIndex the index of the image to be queried.
*
* @return <code>true</code> if the image is tiled.
*
* @exception IllegalStateException if an input source is required
* to determine the return value, but none has been set.
* @exception IndexOutOfBoundsException if an image must be
* accessed to determine the return value, but the supplied index
* is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public boolean isImageTiled(int imageIndex) throws IOException {
return false;
}
/** {@collect.stats}
* Returns the width of a tile in the given image.
*
* <p> The default implementation simply returns
* <code>getWidth(imageIndex)</code>, which is correct for
* non-tiled images. Readers that support tiling should override
* this method.
*
* @return the width of a tile.
*
* @param imageIndex the index of the image to be queried.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getTileWidth(int imageIndex) throws IOException {
return getWidth(imageIndex);
}
/** {@collect.stats}
* Returns the height of a tile in the given image.
*
* <p> The default implementation simply returns
* <code>getHeight(imageIndex)</code>, which is correct for
* non-tiled images. Readers that support tiling should override
* this method.
*
* @return the height of a tile.
*
* @param imageIndex the index of the image to be queried.
*
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getTileHeight(int imageIndex) throws IOException {
return getHeight(imageIndex);
}
/** {@collect.stats}
* Returns the X coordinate of the upper-left corner of tile (0,
* 0) in the given image.
*
* <p> A reader for which the tile grid X offset always has the
* same value (usually 0), may return the value without accessing
* any image data. In such cases, it is not necessary to throw an
* exception even if no input source has been set or the image
* index is out of bounds.
*
* <p> The default implementation simply returns 0, which is
* correct for non-tiled images and tiled images in most formats.
* Readers that support tiling with non-(0, 0) offsets should
* override this method.
*
* @return the X offset of the tile grid.
*
* @param imageIndex the index of the image to be queried.
*
* @exception IllegalStateException if an input source is required
* to determine the return value, but none has been set.
* @exception IndexOutOfBoundsException if an image must be
* accessed to determine the return value, but the supplied index
* is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getTileGridXOffset(int imageIndex) throws IOException {
return 0;
}
/** {@collect.stats}
* Returns the Y coordinate of the upper-left corner of tile (0,
* 0) in the given image.
*
* <p> A reader for which the tile grid Y offset always has the
* same value (usually 0), may return the value without accessing
* any image data. In such cases, it is not necessary to throw an
* exception even if no input source has been set or the image
* index is out of bounds.
*
* <p> The default implementation simply returns 0, which is
* correct for non-tiled images and tiled images in most formats.
* Readers that support tiling with non-(0, 0) offsets should
* override this method.
*
* @return the Y offset of the tile grid.
*
* @param imageIndex the index of the image to be queried.
*
* @exception IllegalStateException if an input source is required
* to determine the return value, but none has been set.
* @exception IndexOutOfBoundsException if an image must be
* accessed to determine the return value, but the supplied index
* is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getTileGridYOffset(int imageIndex) throws IOException {
return 0;
}
/** {@collect.stats}
* Reads the tile indicated by the <code>tileX</code> and
* <code>tileY</code> arguments, returning it as a
* <code>BufferedImage</code>. If the arguments are out of range,
* an <code>IllegalArgumentException</code> is thrown. If the
* image is not tiled, the values 0, 0 will return the entire
* image; any other values will cause an
* <code>IllegalArgumentException</code> to be thrown.
*
* <p> This method is merely a convenience equivalent to calling
* <code>read(int, ImageReadParam)</code> with a read param
* specifiying a source region having offsets of
* <code>tileX*getTileWidth(imageIndex)</code>,
* <code>tileY*getTileHeight(imageIndex)</code> and width and
* height of <code>getTileWidth(imageIndex)</code>,
* <code>getTileHeight(imageIndex)</code>; and subsampling
* factors of 1 and offsets of 0. To subsample a tile, call
* <code>read</code> with a read param specifying this region
* and different subsampling parameters.
*
* <p> The default implementation returns the entire image if
* <code>tileX</code> and <code>tileY</code> are 0, or throws
* an <code>IllegalArgumentException</code> otherwise.
*
* @param imageIndex the index of the image to be retrieved.
* @param tileX the column index (starting with 0) of the tile
* to be retrieved.
* @param tileY the row index (starting with 0) of the tile
* to be retrieved.
*
* @return the tile as a <code>BufferedImage</code>.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is out of bounds.
* @exception IllegalArgumentException if the tile indices are
* out of bounds.
* @exception IOException if an error occurs during reading.
*/
public BufferedImage readTile(int imageIndex,
int tileX, int tileY) throws IOException {
if ((tileX != 0) || (tileY != 0)) {
throw new IllegalArgumentException("Invalid tile indices");
}
return read(imageIndex);
}
/** {@collect.stats}
* Returns a new <code>Raster</code> object containing the raw
* pixel data from the tile, without any color conversion applied.
* The application must determine how to interpret the pixel data by other
* means.
*
* <p> If {@link #canReadRaster <code>canReadRaster()</code>} returns
* <code>false</code>, this method throws an
* <code>UnsupportedOperationException</code>.
*
* <p> The default implementation checks if reading
* <code>Raster</code>s is supported, and if so calls {@link
* #readRaster <code>readRaster(imageIndex, null)</code>} if
* <code>tileX</code> and <code>tileY</code> are 0, or throws an
* <code>IllegalArgumentException</code> otherwise.
*
* @param imageIndex the index of the image to be retrieved.
* @param tileX the column index (starting with 0) of the tile
* to be retrieved.
* @param tileY the row index (starting with 0) of the tile
* to be retrieved.
*
* @return the tile as a <code>Raster</code>.
*
* @exception UnsupportedOperationException if this plug-in does not
* support reading raw <code>Raster</code>s.
* @exception IllegalArgumentException if the tile indices are
* out of bounds.
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is out of bounds.
* @exception IOException if an error occurs during reading.
*
* @see #readTile
* @see #readRaster
* @see java.awt.image.Raster
*/
public Raster readTileRaster(int imageIndex,
int tileX, int tileY) throws IOException {
if (!canReadRaster()) {
throw new UnsupportedOperationException
("readTileRaster not supported!");
}
if ((tileX != 0) || (tileY != 0)) {
throw new IllegalArgumentException("Invalid tile indices");
}
return readRaster(imageIndex, null);
}
// RenderedImages
/** {@collect.stats}
* Returns a <code>RenderedImage</code> object that contains the
* contents of the image indexed by <code>imageIndex</code>. By
* default, the returned image is simply the
* <code>BufferedImage</code> returned by <code>read(imageIndex,
* param)</code>.
*
* <p> The semantics of this method may differ from those of the
* other <code>read</code> methods in several ways. First, any
* destination image and/or image type set in the
* <code>ImageReadParam</code> may be ignored. Second, the usual
* listener calls are not guaranteed to be made, or to be
* meaningful if they are. This is because the returned image may
* not be fully populated with pixel data at the time it is
* returned, or indeed at any time.
*
* <p> If the supplied <code>ImageReadParam</code> contains
* optional setting values not supported by this reader (<i>e.g.</i>
* source render size or any format-specific settings), they will
* be ignored.
*
* <p> The default implementation just calls {@link #read
* <code>read(imageIndex, param)</code>}.
*
* @param imageIndex the index of the image to be retrieved.
* @param param an <code>ImageReadParam</code> used to control
* the reading process, or <code>null</code>.
*
* @return a <code>RenderedImage</code> object providing a view of
* the image.
*
* @exception IllegalStateException if the input source has not been
* set.
* @exception IndexOutOfBoundsException if the supplied index is
* out of bounds.
* @exception IllegalArgumentException if the set of source and
* destination bands specified by
* <code>param.getSourceBands</code> and
* <code>param.getDestinationBands</code> differ in length or
* include indices that are out of bounds.
* @exception IllegalArgumentException if the resulting image
* would have a width or height less than 1.
* @exception IOException if an error occurs during reading.
*/
public RenderedImage readAsRenderedImage(int imageIndex,
ImageReadParam param)
throws IOException {
return read(imageIndex, param);
}
// Thumbnails
/** {@collect.stats}
* Returns <code>true</code> if the image format understood by
* this reader supports thumbnail preview images associated with
* it. The default implementation returns <code>false</code>.
*
* <p> If this method returns <code>false</code>,
* <code>hasThumbnails</code> and <code>getNumThumbnails</code>
* will return <code>false</code> and <code>0</code>,
* respectively, and <code>readThumbnail</code> will throw an
* <code>UnsupportedOperationException</code>, regardless of their
* arguments.
*
* <p> A reader that does not support thumbnails need not
* implement any of the thumbnail-related methods.
*
* @return <code>true</code> if thumbnails are supported.
*/
public boolean readerSupportsThumbnails() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code> if the given image has thumbnail
* preview images associated with it. If the format does not
* support thumbnails (<code>readerSupportsThumbnails</code>
* returns <code>false</code>), <code>false</code> will be
* returned regardless of whether an input source has been set or
* whether <code>imageIndex</code> is in bounds.
*
* <p> The default implementation returns <code>true</code> if
* <code>getNumThumbnails</code> returns a value greater than 0.
*
* @param imageIndex the index of the image being queried.
*
* @return <code>true</code> if the given image has thumbnails.
*
* @exception IllegalStateException if the reader supports
* thumbnails but the input source has not been set.
* @exception IndexOutOfBoundsException if the reader supports
* thumbnails but <code>imageIndex</code> is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public boolean hasThumbnails(int imageIndex) throws IOException {
return getNumThumbnails(imageIndex) > 0;
}
/** {@collect.stats}
* Returns the number of thumbnail preview images associated with
* the given image. If the format does not support thumbnails,
* (<code>readerSupportsThumbnails</code> returns
* <code>false</code>), <code>0</code> will be returned regardless
* of whether an input source has been set or whether
* <code>imageIndex</code> is in bounds.
*
* <p> The default implementation returns 0 without checking its
* argument.
*
* @param imageIndex the index of the image being queried.
*
* @return the number of thumbnails associated with the given
* image.
*
* @exception IllegalStateException if the reader supports
* thumbnails but the input source has not been set.
* @exception IndexOutOfBoundsException if the reader supports
* thumbnails but <code>imageIndex</code> is out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getNumThumbnails(int imageIndex)
throws IOException {
return 0;
}
/** {@collect.stats}
* Returns the width of the thumbnail preview image indexed by
* <code>thumbnailIndex</code>, associated with the image indexed
* by <code>ImageIndex</code>.
*
* <p> If the reader does not support thumbnails,
* (<code>readerSupportsThumbnails</code> returns
* <code>false</code>), an <code>UnsupportedOperationException</code>
* will be thrown.
*
* <p> The default implementation simply returns
* <code>readThumbnail(imageindex,
* thumbnailIndex).getWidth()</code>. Subclasses should therefore
* override this method if possible in order to avoid forcing the
* thumbnail to be read.
*
* @param imageIndex the index of the image to be retrieved.
* @param thumbnailIndex the index of the thumbnail to be retrieved.
*
* @return the width of the desired thumbnail as an <code>int</code>.
*
* @exception UnsupportedOperationException if thumbnails are not
* supported.
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if either of the supplied
* indices are out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getThumbnailWidth(int imageIndex, int thumbnailIndex)
throws IOException {
return readThumbnail(imageIndex, thumbnailIndex).getWidth();
}
/** {@collect.stats}
* Returns the height of the thumbnail preview image indexed by
* <code>thumbnailIndex</code>, associated with the image indexed
* by <code>ImageIndex</code>.
*
* <p> If the reader does not support thumbnails,
* (<code>readerSupportsThumbnails</code> returns
* <code>false</code>), an <code>UnsupportedOperationException</code>
* will be thrown.
*
* <p> The default implementation simply returns
* <code>readThumbnail(imageindex,
* thumbnailIndex).getHeight()</code>. Subclasses should
* therefore override this method if possible in order to avoid
* forcing the thumbnail to be read.
*
* @param imageIndex the index of the image to be retrieved.
* @param thumbnailIndex the index of the thumbnail to be retrieved.
*
* @return the height of the desired thumbnail as an <code>int</code>.
*
* @exception UnsupportedOperationException if thumbnails are not
* supported.
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if either of the supplied
* indices are out of bounds.
* @exception IOException if an error occurs during reading.
*/
public int getThumbnailHeight(int imageIndex, int thumbnailIndex)
throws IOException {
return readThumbnail(imageIndex, thumbnailIndex).getHeight();
}
/** {@collect.stats}
* Returns the thumbnail preview image indexed by
* <code>thumbnailIndex</code>, associated with the image indexed
* by <code>ImageIndex</code> as a <code>BufferedImage</code>.
*
* <p> Any registered <code>IIOReadProgressListener</code> objects
* will be notified by calling their
* <code>thumbnailStarted</code>, <code>thumbnailProgress</code>,
* and <code>thumbnailComplete</code> methods.
*
* <p> If the reader does not support thumbnails,
* (<code>readerSupportsThumbnails</code> returns
* <code>false</code>), an <code>UnsupportedOperationException</code>
* will be thrown regardless of whether an input source has been
* set or whether the indices are in bounds.
*
* <p> The default implementation throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index of the image to be retrieved.
* @param thumbnailIndex the index of the thumbnail to be retrieved.
*
* @return the desired thumbnail as a <code>BufferedImage</code>.
*
* @exception UnsupportedOperationException if thumbnails are not
* supported.
* @exception IllegalStateException if the input source has not been set.
* @exception IndexOutOfBoundsException if either of the supplied
* indices are out of bounds.
* @exception IOException if an error occurs during reading.
*/
public BufferedImage readThumbnail(int imageIndex,
int thumbnailIndex)
throws IOException {
throw new UnsupportedOperationException("Thumbnails not supported!");
}
// Abort
/** {@collect.stats}
* Requests that any current read operation be aborted. The
* contents of the image following the abort will be undefined.
*
* <p> Readers should call <code>clearAbortRequest</code> at the
* beginning of each read operation, and poll the value of
* <code>abortRequested</code> regularly during the read.
*/
public synchronized void abort() {
this.abortFlag = true;
}
/** {@collect.stats}
* Returns <code>true</code> if a request to abort the current
* read operation has been made since the reader was instantiated or
* <code>clearAbortRequest</code> was called.
*
* @return <code>true</code> if the current read operation should
* be aborted.
*
* @see #abort
* @see #clearAbortRequest
*/
protected synchronized boolean abortRequested() {
return this.abortFlag;
}
/** {@collect.stats}
* Clears any previous abort request. After this method has been
* called, <code>abortRequested</code> will return
* <code>false</code>.
*
* @see #abort
* @see #abortRequested
*/
protected synchronized void clearAbortRequest() {
this.abortFlag = false;
}
// Listeners
// Add an element to a list, creating a new list if the
// existing list is null, and return the list.
static List addToList(List l, Object elt) {
if (l == null) {
l = new ArrayList();
}
l.add(elt);
return l;
}
// Remove an element from a list, discarding the list if the
// resulting list is empty, and return the list or null.
static List removeFromList(List l, Object elt) {
if (l == null) {
return l;
}
l.remove(elt);
if (l.size() == 0) {
l = null;
}
return l;
}
/** {@collect.stats}
* Adds an <code>IIOReadWarningListener</code> to the list of
* registered warning listeners. If <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken. Messages sent to the given listener will be
* localized, if possible, to match the current
* <code>Locale</code>. If no <code>Locale</code> has been set,
* warning messages may be localized as the reader sees fit.
*
* @param listener an <code>IIOReadWarningListener</code> to be registered.
*
* @see #removeIIOReadWarningListener
*/
public void addIIOReadWarningListener(IIOReadWarningListener listener) {
if (listener == null) {
return;
}
warningListeners = addToList(warningListeners, listener);
warningLocales = addToList(warningLocales, getLocale());
}
/** {@collect.stats}
* Removes an <code>IIOReadWarningListener</code> from the list of
* registered error listeners. If the listener was not previously
* registered, or if <code>listener</code> is <code>null</code>,
* no exception will be thrown and no action will be taken.
*
* @param listener an IIOReadWarningListener to be unregistered.
*
* @see #addIIOReadWarningListener
*/
public void removeIIOReadWarningListener(IIOReadWarningListener listener) {
if (listener == null || warningListeners == null) {
return;
}
int index = warningListeners.indexOf(listener);
if (index != -1) {
warningListeners.remove(index);
warningLocales.remove(index);
if (warningListeners.size() == 0) {
warningListeners = null;
warningLocales = null;
}
}
}
/** {@collect.stats}
* Removes all currently registered
* <code>IIOReadWarningListener</code> objects.
*
* <p> The default implementation sets the
* <code>warningListeners</code> and <code>warningLocales</code>
* instance variables to <code>null</code>.
*/
public void removeAllIIOReadWarningListeners() {
warningListeners = null;
warningLocales = null;
}
/** {@collect.stats}
* Adds an <code>IIOReadProgressListener</code> to the list of
* registered progress listeners. If <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an IIOReadProgressListener to be registered.
*
* @see #removeIIOReadProgressListener
*/
public void addIIOReadProgressListener(IIOReadProgressListener listener) {
if (listener == null) {
return;
}
progressListeners = addToList(progressListeners, listener);
}
/** {@collect.stats}
* Removes an <code>IIOReadProgressListener</code> from the list
* of registered progress listeners. If the listener was not
* previously registered, or if <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an IIOReadProgressListener to be unregistered.
*
* @see #addIIOReadProgressListener
*/
public void
removeIIOReadProgressListener (IIOReadProgressListener listener) {
if (listener == null || progressListeners == null) {
return;
}
progressListeners = removeFromList(progressListeners, listener);
}
/** {@collect.stats}
* Removes all currently registered
* <code>IIOReadProgressListener</code> objects.
*
* <p> The default implementation sets the
* <code>progressListeners</code> instance variable to
* <code>null</code>.
*/
public void removeAllIIOReadProgressListeners() {
progressListeners = null;
}
/** {@collect.stats}
* Adds an <code>IIOReadUpdateListener</code> to the list of
* registered update listeners. If <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken. The listener will receive notification of pixel
* updates as images and thumbnails are decoded, including the
* starts and ends of progressive passes.
*
* <p> If no update listeners are present, the reader may choose
* to perform fewer updates to the pixels of the destination
* images and/or thumbnails, which may result in more efficient
* decoding.
*
* <p> For example, in progressive JPEG decoding each pass
* contains updates to a set of coefficients, which would have to
* be transformed into pixel values and converted to an RGB color
* space for each pass if listeners are present. If no listeners
* are present, the coefficients may simply be accumulated and the
* final results transformed and color converted one time only.
*
* <p> The final results of decoding will be the same whether or
* not intermediate updates are performed. Thus if only the final
* image is desired it may be perferable not to register any
* <code>IIOReadUpdateListener</code>s. In general, progressive
* updating is most effective when fetching images over a network
* connection that is very slow compared to local CPU processing;
* over a fast connection, progressive updates may actually slow
* down the presentation of the image.
*
* @param listener an IIOReadUpdateListener to be registered.
*
* @see #removeIIOReadUpdateListener
*/
public void
addIIOReadUpdateListener(IIOReadUpdateListener listener) {
if (listener == null) {
return;
}
updateListeners = addToList(updateListeners, listener);
}
/** {@collect.stats}
* Removes an <code>IIOReadUpdateListener</code> from the list of
* registered update listeners. If the listener was not
* previously registered, or if <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an IIOReadUpdateListener to be unregistered.
*
* @see #addIIOReadUpdateListener
*/
public void removeIIOReadUpdateListener(IIOReadUpdateListener listener) {
if (listener == null || updateListeners == null) {
return;
}
updateListeners = removeFromList(updateListeners, listener);
}
/** {@collect.stats}
* Removes all currently registered
* <code>IIOReadUpdateListener</code> objects.
*
* <p> The default implementation sets the
* <code>updateListeners</code> instance variable to
* <code>null</code>.
*/
public void removeAllIIOReadUpdateListeners() {
updateListeners = null;
}
/** {@collect.stats}
* Broadcasts the start of an sequence of image reads to all
* registered <code>IIOReadProgressListener</code>s by calling
* their <code>sequenceStarted</code> method. Subclasses may use
* this method as a convenience.
*
* @param minIndex the lowest index being read.
*/
protected void processSequenceStarted(int minIndex) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.sequenceStarted(this, minIndex);
}
}
/** {@collect.stats}
* Broadcasts the completion of an sequence of image reads to all
* registered <code>IIOReadProgressListener</code>s by calling
* their <code>sequenceComplete</code> method. Subclasses may use
* this method as a convenience.
*/
protected void processSequenceComplete() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.sequenceComplete(this);
}
}
/** {@collect.stats}
* Broadcasts the start of an image read to all registered
* <code>IIOReadProgressListener</code>s by calling their
* <code>imageStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image about to be read.
*/
protected void processImageStarted(int imageIndex) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.imageStarted(this, imageIndex);
}
}
/** {@collect.stats}
* Broadcasts the current percentage of image completion to all
* registered <code>IIOReadProgressListener</code>s by calling
* their <code>imageProgress</code> method. Subclasses may use
* this method as a convenience.
*
* @param percentageDone the current percentage of completion,
* as a <code>float</code>.
*/
protected void processImageProgress(float percentageDone) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.imageProgress(this, percentageDone);
}
}
/** {@collect.stats}
* Broadcasts the completion of an image read to all registered
* <code>IIOReadProgressListener</code>s by calling their
* <code>imageComplete</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processImageComplete() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.imageComplete(this);
}
}
/** {@collect.stats}
* Broadcasts the start of a thumbnail read to all registered
* <code>IIOReadProgressListener</code>s by calling their
* <code>thumbnailStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image associated with the
* thumbnail.
* @param thumbnailIndex the index of the thumbnail.
*/
protected void processThumbnailStarted(int imageIndex,
int thumbnailIndex) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.thumbnailStarted(this, imageIndex, thumbnailIndex);
}
}
/** {@collect.stats}
* Broadcasts the current percentage of thumbnail completion to
* all registered <code>IIOReadProgressListener</code>s by calling
* their <code>thumbnailProgress</code> method. Subclasses may
* use this method as a convenience.
*
* @param percentageDone the current percentage of completion,
* as a <code>float</code>.
*/
protected void processThumbnailProgress(float percentageDone) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.thumbnailProgress(this, percentageDone);
}
}
/** {@collect.stats}
* Broadcasts the completion of a thumbnail read to all registered
* <code>IIOReadProgressListener</code>s by calling their
* <code>thumbnailComplete</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processThumbnailComplete() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.thumbnailComplete(this);
}
}
/** {@collect.stats}
* Broadcasts that the read has been aborted to all registered
* <code>IIOReadProgressListener</code>s by calling their
* <code>readAborted</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processReadAborted() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadProgressListener listener =
(IIOReadProgressListener)progressListeners.get(i);
listener.readAborted(this);
}
}
/** {@collect.stats}
* Broadcasts the beginning of a progressive pass to all
* registered <code>IIOReadUpdateListener</code>s by calling their
* <code>passStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param theImage the <code>BufferedImage</code> being updated.
* @param pass the index of the current pass, starting with 0.
* @param minPass the index of the first pass that will be decoded.
* @param maxPass the index of the last pass that will be decoded.
* @param minX the X coordinate of the upper-left pixel included
* in the pass.
* @param minY the X coordinate of the upper-left pixel included
* in the pass.
* @param periodX the horizontal separation between pixels.
* @param periodY the vertical separation between pixels.
* @param bands an array of <code>int</code>s indicating the
* set of affected bands of the destination.
*/
protected void processPassStarted(BufferedImage theImage,
int pass,
int minPass, int maxPass,
int minX, int minY,
int periodX, int periodY,
int[] bands) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.passStarted(this, theImage, pass,
minPass,
maxPass,
minX, minY,
periodX, periodY,
bands);
}
}
/** {@collect.stats}
* Broadcasts the update of a set of samples to all registered
* <code>IIOReadUpdateListener</code>s by calling their
* <code>imageUpdate</code> method. Subclasses may use this
* method as a convenience.
*
* @param theImage the <code>BufferedImage</code> being updated.
* @param minX the X coordinate of the upper-left pixel included
* in the pass.
* @param minY the X coordinate of the upper-left pixel included
* in the pass.
* @param width the total width of the area being updated, including
* pixels being skipped if <code>periodX > 1</code>.
* @param height the total height of the area being updated,
* including pixels being skipped if <code>periodY > 1</code>.
* @param periodX the horizontal separation between pixels.
* @param periodY the vertical separation between pixels.
* @param bands an array of <code>int</code>s indicating the
* set of affected bands of the destination.
*/
protected void processImageUpdate(BufferedImage theImage,
int minX, int minY,
int width, int height,
int periodX, int periodY,
int[] bands) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.imageUpdate(this,
theImage,
minX, minY,
width, height,
periodX, periodY,
bands);
}
}
/** {@collect.stats}
* Broadcasts the end of a progressive pass to all
* registered <code>IIOReadUpdateListener</code>s by calling their
* <code>passComplete</code> method. Subclasses may use this
* method as a convenience.
*
* @param theImage the <code>BufferedImage</code> being updated.
*/
protected void processPassComplete(BufferedImage theImage) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.passComplete(this, theImage);
}
}
/** {@collect.stats}
* Broadcasts the beginning of a thumbnail progressive pass to all
* registered <code>IIOReadUpdateListener</code>s by calling their
* <code>thumbnailPassStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
* @param pass the index of the current pass, starting with 0.
* @param minPass the index of the first pass that will be decoded.
* @param maxPass the index of the last pass that will be decoded.
* @param minX the X coordinate of the upper-left pixel included
* in the pass.
* @param minY the X coordinate of the upper-left pixel included
* in the pass.
* @param periodX the horizontal separation between pixels.
* @param periodY the vertical separation between pixels.
* @param bands an array of <code>int</code>s indicating the
* set of affected bands of the destination.
*/
protected void processThumbnailPassStarted(BufferedImage theThumbnail,
int pass,
int minPass, int maxPass,
int minX, int minY,
int periodX, int periodY,
int[] bands) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.thumbnailPassStarted(this, theThumbnail, pass,
minPass,
maxPass,
minX, minY,
periodX, periodY,
bands);
}
}
/** {@collect.stats}
* Broadcasts the update of a set of samples in a thumbnail image
* to all registered <code>IIOReadUpdateListener</code>s by
* calling their <code>thumbnailUpdate</code> method. Subclasses may
* use this method as a convenience.
*
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
* @param minX the X coordinate of the upper-left pixel included
* in the pass.
* @param minY the X coordinate of the upper-left pixel included
* in the pass.
* @param width the total width of the area being updated, including
* pixels being skipped if <code>periodX > 1</code>.
* @param height the total height of the area being updated,
* including pixels being skipped if <code>periodY > 1</code>.
* @param periodX the horizontal separation between pixels.
* @param periodY the vertical separation between pixels.
* @param bands an array of <code>int</code>s indicating the
* set of affected bands of the destination.
*/
protected void processThumbnailUpdate(BufferedImage theThumbnail,
int minX, int minY,
int width, int height,
int periodX, int periodY,
int[] bands) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.thumbnailUpdate(this,
theThumbnail,
minX, minY,
width, height,
periodX, periodY,
bands);
}
}
/** {@collect.stats}
* Broadcasts the end of a thumbnail progressive pass to all
* registered <code>IIOReadUpdateListener</code>s by calling their
* <code>thumbnailPassComplete</code> method. Subclasses may use this
* method as a convenience.
*
* @param theThumbnail the <code>BufferedImage</code> thumbnail
* being updated.
*/
protected void processThumbnailPassComplete(BufferedImage theThumbnail) {
if (updateListeners == null) {
return;
}
int numListeners = updateListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadUpdateListener listener =
(IIOReadUpdateListener)updateListeners.get(i);
listener.thumbnailPassComplete(this, theThumbnail);
}
}
/** {@collect.stats}
* Broadcasts a warning message to all registered
* <code>IIOReadWarningListener</code>s by calling their
* <code>warningOccurred</code> method. Subclasses may use this
* method as a convenience.
*
* @param warning the warning message to send.
*
* @exception IllegalArgumentException if <code>warning</code>
* is <code>null</code>.
*/
protected void processWarningOccurred(String warning) {
if (warningListeners == null) {
return;
}
if (warning == null) {
throw new IllegalArgumentException("warning == null!");
}
int numListeners = warningListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadWarningListener listener =
(IIOReadWarningListener)warningListeners.get(i);
listener.warningOccurred(this, warning);
}
}
/** {@collect.stats}
* Broadcasts a localized warning message to all registered
* <code>IIOReadWarningListener</code>s by calling their
* <code>warningOccurred</code> method with a string taken
* from a <code>ResourceBundle</code>. Subclasses may use this
* method as a convenience.
*
* @param baseName the base name of a set of
* <code>ResourceBundle</code>s containing localized warning
* messages.
* @param keyword the keyword used to index the warning message
* within the set of <code>ResourceBundle</code>s.
*
* @exception IllegalArgumentException if <code>baseName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>keyword</code>
* is <code>null</code>.
* @exception IllegalArgumentException if no appropriate
* <code>ResourceBundle</code> may be located.
* @exception IllegalArgumentException if the named resource is
* not found in the located <code>ResourceBundle</code>.
* @exception IllegalArgumentException if the object retrieved
* from the <code>ResourceBundle</code> is not a
* <code>String</code>.
*/
protected void processWarningOccurred(String baseName,
String keyword) {
if (warningListeners == null) {
return;
}
if (baseName == null) {
throw new IllegalArgumentException("baseName == null!");
}
if (keyword == null) {
throw new IllegalArgumentException("keyword == null!");
}
int numListeners = warningListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOReadWarningListener listener =
(IIOReadWarningListener)warningListeners.get(i);
Locale locale = (Locale)warningLocales.get(i);
if (locale == null) {
locale = Locale.getDefault();
}
/** {@collect.stats}
* If an applet supplies an implementation of ImageReader and
* resource bundles, then the resource bundle will need to be
* accessed via the applet class loader. So first try the context
* class loader to locate the resource bundle.
* If that throws MissingResourceException, then try the
* system class loader.
*/
ClassLoader loader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
ResourceBundle bundle = null;
try {
bundle = ResourceBundle.getBundle(baseName, locale, loader);
} catch (MissingResourceException mre) {
try {
bundle = ResourceBundle.getBundle(baseName, locale);
} catch (MissingResourceException mre1) {
throw new IllegalArgumentException("Bundle not found!");
}
}
String warning = null;
try {
warning = bundle.getString(keyword);
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Resource is not a String!");
} catch (MissingResourceException mre) {
throw new IllegalArgumentException("Resource is missing!");
}
listener.warningOccurred(this, warning);
}
}
// State management
/** {@collect.stats}
* Restores the <code>ImageReader</code> to its initial state.
*
* <p> The default implementation calls <code>setInput(null,
* false)</code>, <code>setLocale(null)</code>,
* <code>removeAllIIOReadUpdateListeners()</code>,
* <code>removeAllIIOReadWarningListeners()</code>,
* <code>removeAllIIOReadProgressListeners()</code>, and
* <code>clearAbortRequest</code>.
*/
public void reset() {
setInput(null, false, false);
setLocale(null);
removeAllIIOReadUpdateListeners();
removeAllIIOReadProgressListeners();
removeAllIIOReadWarningListeners();
clearAbortRequest();
}
/** {@collect.stats}
* Allows any resources held by this object to be released. The
* result of calling any other method (other than
* <code>finalize</code>) subsequent to a call to this method
* is undefined.
*
* <p>It is important for applications to call this method when they
* know they will no longer be using this <code>ImageReader</code>.
* Otherwise, the reader may continue to hold on to resources
* indefinitely.
*
* <p>The default implementation of this method in the superclass does
* nothing. Subclass implementations should ensure that all resources,
* especially native resources, are released.
*/
public void dispose() {
}
// Utility methods
/** {@collect.stats}
* A utility method that may be used by readers to compute the
* region of the source image that should be read, taking into
* account any source region and subsampling offset settings in
* the supplied <code>ImageReadParam</code>. The actual
* subsampling factors, destination size, and destination offset
* are <em>not</em> taken into consideration, thus further
* clipping must take place. The {@link #computeRegions
* <code>computeRegions</code>} method performs all necessary
* clipping.
*
* @param param the <code>ImageReadParam</code> being used, or
* <code>null</code>.
* @param srcWidth the width of the source image.
* @param srcHeight the height of the source image.
*
* @return the source region as a <code>Rectangle</code>.
*/
protected static Rectangle getSourceRegion(ImageReadParam param,
int srcWidth,
int srcHeight) {
Rectangle sourceRegion = new Rectangle(0, 0, srcWidth, srcHeight);
if (param != null) {
Rectangle region = param.getSourceRegion();
if (region != null) {
sourceRegion = sourceRegion.intersection(region);
}
int subsampleXOffset = param.getSubsamplingXOffset();
int subsampleYOffset = param.getSubsamplingYOffset();
sourceRegion.x += subsampleXOffset;
sourceRegion.y += subsampleYOffset;
sourceRegion.width -= subsampleXOffset;
sourceRegion.height -= subsampleYOffset;
}
return sourceRegion;
}
/** {@collect.stats}
* Computes the source region of interest and the destination
* region of interest, taking the width and height of the source
* image, an optional destination image, and an optional
* <code>ImageReadParam</code> into account. The source region
* begins with the entire source image. Then that is clipped to
* the source region specified in the <code>ImageReadParam</code>,
* if one is specified.
*
* <p> If either of the destination offsets are negative, the
* source region is clipped so that its top left will coincide
* with the top left of the destination image, taking subsampling
* into account. Then the result is clipped to the destination
* image on the right and bottom, if one is specified, taking
* subsampling and destination offsets into account.
*
* <p> Similarly, the destination region begins with the source
* image, is translated to the destination offset given in the
* <code>ImageReadParam</code> if there is one, and finally is
* clipped to the destination image, if there is one.
*
* <p> If either the source or destination regions end up having a
* width or height of 0, an <code>IllegalArgumentException</code>
* is thrown.
*
* <p> The {@link #getSourceRegion <code>getSourceRegion</code>}
* method may be used if only source clipping is desired.
*
* @param param an <code>ImageReadParam</code>, or <code>null</code>.
* @param srcWidth the width of the source image.
* @param srcHeight the height of the source image.
* @param image a <code>BufferedImage</code> that will be the
* destination image, or <code>null</code>.
* @param srcRegion a <code>Rectangle</code> that will be filled with
* the source region of interest.
* @param destRegion a <code>Rectangle</code> that will be filled with
* the destination region of interest.
* @exception IllegalArgumentException if <code>srcRegion</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>dstRegion</code>
* is <code>null</code>.
* @exception IllegalArgumentException if the resulting source or
* destination region is empty.
*/
protected static void computeRegions(ImageReadParam param,
int srcWidth,
int srcHeight,
BufferedImage image,
Rectangle srcRegion,
Rectangle destRegion) {
if (srcRegion == null) {
throw new IllegalArgumentException("srcRegion == null!");
}
if (destRegion == null) {
throw new IllegalArgumentException("destRegion == null!");
}
// Start with the entire source image
srcRegion.setBounds(0, 0, srcWidth, srcHeight);
// Destination also starts with source image, as that is the
// maximum extent if there is no subsampling
destRegion.setBounds(0, 0, srcWidth, srcHeight);
// Clip that to the param region, if there is one
int periodX = 1;
int periodY = 1;
int gridX = 0;
int gridY = 0;
if (param != null) {
Rectangle paramSrcRegion = param.getSourceRegion();
if (paramSrcRegion != null) {
srcRegion.setBounds(srcRegion.intersection(paramSrcRegion));
}
periodX = param.getSourceXSubsampling();
periodY = param.getSourceYSubsampling();
gridX = param.getSubsamplingXOffset();
gridY = param.getSubsamplingYOffset();
srcRegion.translate(gridX, gridY);
srcRegion.width -= gridX;
srcRegion.height -= gridY;
destRegion.setLocation(param.getDestinationOffset());
}
// Now clip any negative destination offsets, i.e. clip
// to the top and left of the destination image
if (destRegion.x < 0) {
int delta = -destRegion.x*periodX;
srcRegion.x += delta;
srcRegion.width -= delta;
destRegion.x = 0;
}
if (destRegion.y < 0) {
int delta = -destRegion.y*periodY;
srcRegion.y += delta;
srcRegion.height -= delta;
destRegion.y = 0;
}
// Now clip the destination Region to the subsampled width and height
int subsampledWidth = (srcRegion.width + periodX - 1)/periodX;
int subsampledHeight = (srcRegion.height + periodY - 1)/periodY;
destRegion.width = subsampledWidth;
destRegion.height = subsampledHeight;
// Now clip that to right and bottom of the destination image,
// if there is one, taking subsampling into account
if (image != null) {
Rectangle destImageRect = new Rectangle(0, 0,
image.getWidth(),
image.getHeight());
destRegion.setBounds(destRegion.intersection(destImageRect));
if (destRegion.isEmpty()) {
throw new IllegalArgumentException
("Empty destination region!");
}
int deltaX = destRegion.x + subsampledWidth - image.getWidth();
if (deltaX > 0) {
srcRegion.width -= deltaX*periodX;
}
int deltaY = destRegion.y + subsampledHeight - image.getHeight();
if (deltaY > 0) {
srcRegion.height -= deltaY*periodY;
}
}
if (srcRegion.isEmpty() || destRegion.isEmpty()) {
throw new IllegalArgumentException("Empty region!");
}
}
/** {@collect.stats}
* A utility method that may be used by readers to test the
* validity of the source and destination band settings of an
* <code>ImageReadParam</code>. This method may be called as soon
* as the reader knows both the number of bands of the source
* image as it exists in the input stream, and the number of bands
* of the destination image that being written.
*
* <p> The method retrieves the source and destination band
* setting arrays from param using the <code>getSourceBands</code>
* and <code>getDestinationBands</code>methods (or considers them
* to be <code>null</code> if <code>param</code> is
* <code>null</code>). If the source band setting array is
* <code>null</code>, it is considered to be equal to the array
* <code>{ 0, 1, ..., numSrcBands - 1 }</code>, and similarly for
* the destination band setting array.
*
* <p> The method then tests that both arrays are equal in length,
* and that neither array contains a value larger than the largest
* available band index.
*
* <p> Any failure results in an
* <code>IllegalArgumentException</code> being thrown; success
* results in the method returning silently.
*
* @param param the <code>ImageReadParam</code> being used to read
* the image.
* @param numSrcBands the number of bands of the image as it exists
* int the input source.
* @param numDstBands the number of bands in the destination image
* being written.
*
* @exception IllegalArgumentException if <code>param</code>
* contains an invalid specification of a source and/or
* destination band subset.
*/
protected static void checkReadParamBandSettings(ImageReadParam param,
int numSrcBands,
int numDstBands) {
// A null param is equivalent to srcBands == dstBands == null.
int[] srcBands = null;
int[] dstBands = null;
if (param != null) {
srcBands = param.getSourceBands();
dstBands = param.getDestinationBands();
}
int paramSrcBandLength =
(srcBands == null) ? numSrcBands : srcBands.length;
int paramDstBandLength =
(dstBands == null) ? numDstBands : dstBands.length;
if (paramSrcBandLength != paramDstBandLength) {
throw new IllegalArgumentException("ImageReadParam num source & dest bands differ!");
}
if (srcBands != null) {
for (int i = 0; i < srcBands.length; i++) {
if (srcBands[i] >= numSrcBands) {
throw new IllegalArgumentException("ImageReadParam source bands contains a value >= the number of source bands!");
}
}
}
if (dstBands != null) {
for (int i = 0; i < dstBands.length; i++) {
if (dstBands[i] >= numDstBands) {
throw new IllegalArgumentException("ImageReadParam dest bands contains a value >= the number of dest bands!");
}
}
}
}
/** {@collect.stats}
* Returns the <code>BufferedImage</code> to which decoded pixel
* data should be written. The image is determined by inspecting
* the supplied <code>ImageReadParam</code> if it is
* non-<code>null</code>; if its <code>getDestination</code>
* method returns a non-<code>null</code> value, that image is
* simply returned. Otherwise,
* <code>param.getDestinationType</code> method is called to
* determine if a particular image type has been specified. If
* so, the returned <code>ImageTypeSpecifier</code> is used after
* checking that it is equal to one of those included in
* <code>imageTypes</code>.
*
* <p> If <code>param</code> is <code>null</code> or the above
* steps have not yielded an image or an
* <code>ImageTypeSpecifier</code>, the first value obtained from
* the <code>imageTypes</code> parameter is used. Typically, the
* caller will set <code>imageTypes</code> to the value of
* <code>getImageTypes(imageIndex)</code>.
*
* <p> Next, the dimensions of the image are determined by a call
* to <code>computeRegions</code>. The actual width and height of
* the image being decoded are passed in as the <code>width</code>
* and <code>height</code> parameters.
*
* @param param an <code>ImageReadParam</code> to be used to get
* the destination image or image type, or <code>null</code>.
* @param imageTypes an <code>Iterator</code> of
* <code>ImageTypeSpecifier</code>s indicating the legal image
* types, with the default first.
* @param width the true width of the image or tile begin decoded.
* @param height the true width of the image or tile being decoded.
*
* @return the <code>BufferedImage</code> to which decoded pixel
* data should be written.
*
* @exception IIOException if the <code>ImageTypeSpecifier</code>
* specified by <code>param</code> does not match any of the legal
* ones from <code>imageTypes</code>.
* @exception IllegalArgumentException if <code>imageTypes</code>
* is <code>null</code> or empty, or if an object not of type
* <code>ImageTypeSpecifier</code> is retrieved from it.
* @exception IllegalArgumentException if the resulting image would
* have a width or height less than 1.
* @exception IllegalArgumentException if the product of
* <code>width</code> and <code>height</code> is greater than
* <code>Integer.MAX_VALUE</code>.
*/
protected static BufferedImage
getDestination(ImageReadParam param,
Iterator<ImageTypeSpecifier> imageTypes,
int width, int height)
throws IIOException {
if (imageTypes == null || !imageTypes.hasNext()) {
throw new IllegalArgumentException("imageTypes null or empty!");
}
if ((long)width*height > Integer.MAX_VALUE) {
throw new IllegalArgumentException
("width*height > Integer.MAX_VALUE!");
}
BufferedImage dest = null;
ImageTypeSpecifier imageType = null;
// If param is non-null, use it
if (param != null) {
// Try to get the image itself
dest = param.getDestination();
if (dest != null) {
return dest;
}
// No image, get the image type
imageType = param.getDestinationType();
}
// No info from param, use fallback image type
if (imageType == null) {
Object o = imageTypes.next();
if (!(o instanceof ImageTypeSpecifier)) {
throw new IllegalArgumentException
("Non-ImageTypeSpecifier retrieved from imageTypes!");
}
imageType = (ImageTypeSpecifier)o;
} else {
boolean foundIt = false;
while (imageTypes.hasNext()) {
ImageTypeSpecifier type =
(ImageTypeSpecifier)imageTypes.next();
if (type.equals(imageType)) {
foundIt = true;
break;
}
}
if (!foundIt) {
throw new IIOException
("Destination type from ImageReadParam does not match!");
}
}
Rectangle srcRegion = new Rectangle(0,0,0,0);
Rectangle destRegion = new Rectangle(0,0,0,0);
computeRegions(param,
width,
height,
null,
srcRegion,
destRegion);
int destWidth = destRegion.x + destRegion.width;
int destHeight = destRegion.y + destRegion.height;
// Create a new image based on the type specifier
return imageType.createBufferedImage(destWidth, destHeight);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Point;
import java.awt.Rectangle;
/** {@collect.stats}
* A superclass of all classes describing how streams should be
* decoded or encoded. This class contains all the variables and
* methods that are shared by <code>ImageReadParam</code> and
* <code>ImageWriteParam</code>.
*
* <p> This class provides mechanisms to specify a source region and a
* destination region. When reading, the source is the stream and
* the in-memory image is the destination. When writing, these are
* reversed. In the case of writing, destination regions may be used
* only with a writer that supports pixel replacement.
* <p>
* Decimation subsampling may be specified for both readers
* and writers, using a movable subsampling grid.
* <p>
* Subsets of the source and destination bands may be selected.
*
*/
public abstract class IIOParam {
/** {@collect.stats}
* The source region, on <code>null</code> if none is set.
*/
protected Rectangle sourceRegion = null;
/** {@collect.stats}
* The decimation subsampling to be applied in the horizontal
* direction. By default, the value is <code>1</code>.
* The value must not be negative or 0.
*/
protected int sourceXSubsampling = 1;
/** {@collect.stats}
* The decimation subsampling to be applied in the vertical
* direction. By default, the value is <code>1</code>.
* The value must not be negative or 0.
*/
protected int sourceYSubsampling = 1;
/** {@collect.stats}
* A horizontal offset to be applied to the subsampling grid before
* subsampling. The first pixel to be used will be offset this
* amount from the origin of the region, or of the image if no
* region is specified.
*/
protected int subsamplingXOffset = 0;
/** {@collect.stats}
* A vertical offset to be applied to the subsampling grid before
* subsampling. The first pixel to be used will be offset this
* amount from the origin of the region, or of the image if no
* region is specified.
*/
protected int subsamplingYOffset = 0;
/** {@collect.stats}
* An array of <code>int</code>s indicating which source bands
* will be used, or <code>null</code>. If <code>null</code>, the
* set of source bands to be used is as described in the comment
* for the <code>setSourceBands</code> method. No value should
* be allowed to be negative.
*/
protected int[] sourceBands = null;
/** {@collect.stats}
* An <code>ImageTypeSpecifier</code> to be used to generate a
* destination image when reading, or to set the output color type
* when writing. If non has been setm the value will be
* <code>null</code>. By default, the value is <code>null</code>.
*/
protected ImageTypeSpecifier destinationType = null;
/** {@collect.stats}
* The offset in the destination where the upper-left decoded
* pixel should be placed. By default, the value is (0, 0).
*/
protected Point destinationOffset = new Point(0, 0);
/** {@collect.stats}
* The default <code>IIOParamController</code> that will be
* used to provide settings for this <code>IIOParam</code>
* object when the <code>activateController</code> method
* is called. This default should be set by subclasses
* that choose to provide their own default controller,
* usually a GUI, for setting parameters.
*
* @see IIOParamController
* @see #getDefaultController
* @see #activateController
*/
protected IIOParamController defaultController = null;
/** {@collect.stats}
* The <code>IIOParamController</code> that will be
* used to provide settings for this <code>IIOParam</code>
* object when the <code>activateController</code> method
* is called. This value overrides any default controller,
* even when null.
*
* @see IIOParamController
* @see #setController(IIOParamController)
* @see #hasController()
* @see #activateController()
*/
protected IIOParamController controller = null;
/** {@collect.stats}
* Protected constructor may be called only by subclasses.
*/
protected IIOParam() {
controller = defaultController;
}
/** {@collect.stats}
* Sets the source region of interest. The region of interest is
* described as a rectangle, with the upper-left corner of the
* source image as pixel (0, 0) and increasing values down and to
* the right. The actual number of pixels used will depend on
* the subsampling factors set by <code>setSourceSubsampling</code>.
* If subsampling has been set such that this number is zero,
* an <code>IllegalStateException</code> will be thrown.
*
* <p> The source region of interest specified by this method will
* be clipped as needed to fit within the source bounds, as well
* as the destination offsets, width, and height at the time of
* actual I/O.
*
* <p> A value of <code>null</code> for <code>sourceRegion</code>
* will remove any region specification, causing the entire image
* to be used.
*
* @param sourceRegion a <code>Rectangle</code> specifying the
* source region of interest, or <code>null</code>.
*
* @exception IllegalArgumentException if
* <code>sourceRegion</code> is non-<code>null</code> and either
* <code>sourceRegion.x</code> or <code>sourceRegion.y</code> is
* negative.
* @exception IllegalArgumentException if
* <code>sourceRegion</code> is non-<code>null</code> and either
* <code>sourceRegion.width</code> or
* <code>sourceRegion.height</code> is negative or 0.
* @exception IllegalStateException if subsampling is such that
* this region will have a subsampled width or height of zero.
*
* @see #getSourceRegion
* @see #setSourceSubsampling
* @see ImageReadParam#setDestinationOffset
* @see ImageReadParam#getDestinationOffset
*/
public void setSourceRegion(Rectangle sourceRegion) {
if (sourceRegion == null) {
this.sourceRegion = null;
return;
}
if (sourceRegion.x < 0) {
throw new IllegalArgumentException("sourceRegion.x < 0!");
}
if (sourceRegion.y < 0){
throw new IllegalArgumentException("sourceRegion.y < 0!");
}
if (sourceRegion.width <= 0) {
throw new IllegalArgumentException("sourceRegion.width <= 0!");
}
if (sourceRegion.height <= 0) {
throw new IllegalArgumentException("sourceRegion.height <= 0!");
}
// Throw an IllegalStateException if region falls between subsamples
if (sourceRegion.width <= subsamplingXOffset) {
throw new IllegalStateException
("sourceRegion.width <= subsamplingXOffset!");
}
if (sourceRegion.height <= subsamplingYOffset) {
throw new IllegalStateException
("sourceRegion.height <= subsamplingYOffset!");
}
this.sourceRegion = (Rectangle)sourceRegion.clone();
}
/** {@collect.stats}
* Returns the source region to be used. The returned value is
* that set by the most recent call to
* <code>setSourceRegion</code>, and will be <code>null</code> if
* there is no region set.
*
* @return the source region of interest as a
* <code>Rectangle</code>, or <code>null</code>.
*
* @see #setSourceRegion
*/
public Rectangle getSourceRegion() {
if (sourceRegion == null) {
return null;
}
return (Rectangle)sourceRegion.clone();
}
/** {@collect.stats}
* Specifies a decimation subsampling to apply on I/O. The
* <code>sourceXSubsampling</code> and
* <code>sourceYSubsampling</code> parameters specify the
* subsampling period (<i>i.e.</i>, the number of rows and columns
* to advance after every source pixel). Specifically, a period of
* 1 will use every row or column; a period of 2 will use every
* other row or column. The <code>subsamplingXOffset</code> and
* <code>subsamplingYOffset</code> parameters specify an offset
* from the region (or image) origin for the first subsampled pixel.
* Adjusting the origin of the subsample grid is useful for avoiding
* seams when subsampling a very large source image into destination
* regions that will be assembled into a complete subsampled image.
* Most users will want to simply leave these parameters at 0.
*
* <p> The number of pixels and scanlines to be used are calculated
* as follows.
* <p>
* The number of subsampled pixels in a scanline is given by
* <p>
* <code>truncate[(width - subsamplingXOffset + sourceXSubsampling - 1)
* / sourceXSubsampling]</code>.
* <p>
* If the region is such that this width is zero, an
* <code>IllegalStateException</code> is thrown.
* <p>
* The number of scanlines to be used can be computed similarly.
*
* <p>The ability to set the subsampling grid to start somewhere
* other than the source region origin is useful if the
* region is being used to create subsampled tiles of a large image,
* where the tile width and height are not multiples of the
* subsampling periods. If the subsampling grid does not remain
* consistent from tile to tile, there will be artifacts at the tile
* boundaries. By adjusting the subsampling grid offset for each
* tile to compensate, these artifacts can be avoided. The tradeoff
* is that in order to avoid these artifacts, the tiles are not all
* the same size. The grid offset to use in this case is given by:
* <br>
* grid offset = [period - (region offset modulo period)] modulo period)
*
* <p> If either <code>sourceXSubsampling</code> or
* <code>sourceYSubsampling</code> is 0 or negative, an
* <code>IllegalArgumentException</code> will be thrown.
*
* <p> If either <code>subsamplingXOffset</code> or
* <code>subsamplingYOffset</code> is negative or greater than or
* equal to the corresponding period, an
* <code>IllegalArgumentException</code> will be thrown.
*
* <p> There is no <code>unsetSourceSubsampling</code> method;
* simply call <code>setSourceSubsampling(1, 1, 0, 0)</code> to
* restore default values.
*
* @param sourceXSubsampling the number of columns to advance
* between pixels.
* @param sourceYSubsampling the number of rows to advance between
* pixels.
* @param subsamplingXOffset the horizontal offset of the first subsample
* within the region, or within the image if no region is set.
* @param subsamplingYOffset the horizontal offset of the first subsample
* within the region, or within the image if no region is set.
* @exception IllegalArgumentException if either period is
* negative or 0, or if either grid offset is negative or greater than
* the corresponding period.
* @exception IllegalStateException if the source region is such that
* the subsampled output would contain no pixels.
*/
public void setSourceSubsampling(int sourceXSubsampling,
int sourceYSubsampling,
int subsamplingXOffset,
int subsamplingYOffset) {
if (sourceXSubsampling <= 0) {
throw new IllegalArgumentException("sourceXSubsampling <= 0!");
}
if (sourceYSubsampling <= 0) {
throw new IllegalArgumentException("sourceYSubsampling <= 0!");
}
if (subsamplingXOffset < 0 ||
subsamplingXOffset >= sourceXSubsampling) {
throw new IllegalArgumentException
("subsamplingXOffset out of range!");
}
if (subsamplingYOffset < 0 ||
subsamplingYOffset >= sourceYSubsampling) {
throw new IllegalArgumentException
("subsamplingYOffset out of range!");
}
// Throw an IllegalStateException if region falls between subsamples
if (sourceRegion != null) {
if (subsamplingXOffset >= sourceRegion.width ||
subsamplingYOffset >= sourceRegion.height) {
throw new IllegalStateException("region contains no pixels!");
}
}
this.sourceXSubsampling = sourceXSubsampling;
this.sourceYSubsampling = sourceYSubsampling;
this.subsamplingXOffset = subsamplingXOffset;
this.subsamplingYOffset = subsamplingYOffset;
}
/** {@collect.stats}
* Returns the number of source columns to advance for each pixel.
*
* <p>If <code>setSourceSubsampling</code> has not been called, 1
* is returned (which is the correct value).
*
* @return the source subsampling X period.
*
* @see #setSourceSubsampling
* @see #getSourceYSubsampling
*/
public int getSourceXSubsampling() {
return sourceXSubsampling;
}
/** {@collect.stats}
* Returns the number of rows to advance for each pixel.
*
* <p>If <code>setSourceSubsampling</code> has not been called, 1
* is returned (which is the correct value).
*
* @return the source subsampling Y period.
*
* @see #setSourceSubsampling
* @see #getSourceXSubsampling
*/
public int getSourceYSubsampling() {
return sourceYSubsampling;
}
/** {@collect.stats}
* Returns the horizontal offset of the subsampling grid.
*
* <p>If <code>setSourceSubsampling</code> has not been called, 0
* is returned (which is the correct value).
*
* @return the source subsampling grid X offset.
*
* @see #setSourceSubsampling
* @see #getSubsamplingYOffset
*/
public int getSubsamplingXOffset() {
return subsamplingXOffset;
}
/** {@collect.stats}
* Returns the vertical offset of the subsampling grid.
*
* <p>If <code>setSourceSubsampling</code> has not been called, 0
* is returned (which is the correct value).
*
* @return the source subsampling grid Y offset.
*
* @see #setSourceSubsampling
* @see #getSubsamplingXOffset
*/
public int getSubsamplingYOffset() {
return subsamplingYOffset;
}
/** {@collect.stats}
* Sets the indices of the source bands to be used. Duplicate
* indices are not allowed.
*
* <p> A <code>null</code> value indicates that all source bands
* will be used.
*
* <p> At the time of reading, an
* <code>IllegalArgumentException</code> will be thrown by the
* reader or writer if a value larger than the largest available
* source band index has been specified or if the number of source
* bands and destination bands to be used differ. The
* <code>ImageReader.checkReadParamBandSettings</code> method may
* be used to automate this test.
*
* <p> Semantically, a copy is made of the array; changes to the
* array contents subsequent to this call have no effect on
* this <code>IIOParam</code>.
*
* @param sourceBands an array of integer band indices to be
* used.
*
* @exception IllegalArgumentException if <code>sourceBands</code>
* contains a negative or duplicate value.
*
* @see #getSourceBands
* @see ImageReadParam#setDestinationBands
* @see ImageReader#checkReadParamBandSettings
*/
public void setSourceBands(int[] sourceBands) {
if (sourceBands == null) {
this.sourceBands = null;
} else {
int numBands = sourceBands.length;
for (int i = 0; i < numBands; i++) {
int band = sourceBands[i];
if (band < 0) {
throw new IllegalArgumentException("Band value < 0!");
}
for (int j = i + 1; j < numBands; j++) {
if (band == sourceBands[j]) {
throw new IllegalArgumentException("Duplicate band value!");
}
}
}
this.sourceBands = (int[])(sourceBands.clone());
}
}
/** {@collect.stats}
* Returns the set of of source bands to be used. The returned
* value is that set by the most recent call to
* <code>setSourceBands</code>, or <code>null</code> if there have
* been no calls to <code>setSourceBands</code>.
*
* <p> Semantically, the array returned is a copy; changes to
* array contents subsequent to this call have no effect on this
* <code>IIOParam</code>.
*
* @return the set of source bands to be used, or
* <code>null</code>.
*
* @see #setSourceBands
*/
public int[] getSourceBands() {
if (sourceBands == null) {
return null;
}
return (int[])(sourceBands.clone());
}
/** {@collect.stats}
* Sets the desired image type for the destination image, using an
* <code>ImageTypeSpecifier</code>.
*
* <p> When reading, if the layout of the destination has been set
* using this method, each call to an <code>ImageReader</code>
* <code>read</code> method will return a new
* <code>BufferedImage</code> using the format specified by the
* supplied type specifier. As a side effect, any destination
* <code>BufferedImage</code> set by
* <code>ImageReadParam.setDestination(BufferedImage)</code> will
* no longer be set as the destination. In other words, this
* method may be thought of as calling
* <code>setDestination((BufferedImage)null)</code>.
*
* <p> When writing, the destination type maybe used to determine
* the color type of the image. The <code>SampleModel</code>
* information will be ignored, and may be <code>null</code>. For
* example, a 4-banded image could represent either CMYK or RGBA
* data. If a destination type is set, its
* <code>ColorModel</code> will override any
* <code>ColorModel</code> on the image itself. This is crucial
* when <code>setSourceBands</code> is used since the image's
* <code>ColorModel</code> will refer to the entire image rather
* than to the subset of bands being written.
*
* @param destinationType the <code>ImageTypeSpecifier</code> to
* be used to determine the destination layout and color type.
*
* @see #getDestinationType
*/
public void setDestinationType(ImageTypeSpecifier destinationType) {
this.destinationType = destinationType;
}
/** {@collect.stats}
* Returns the type of image to be returned by the read, if one
* was set by a call to
* <code>setDestination(ImageTypeSpecifier)</code>, as an
* <code>ImageTypeSpecifier</code>. If none was set,
* <code>null</code> is returned.
*
* @return an <code>ImageTypeSpecifier</code> describing the
* destination type, or <code>null</code>.
*
* @see #setDestinationType
*/
public ImageTypeSpecifier getDestinationType() {
return destinationType;
}
/** {@collect.stats}
* Specifies the offset in the destination image at which future
* decoded pixels are to be placed, when reading, or where a
* region will be written, when writing.
*
* <p> When reading, the region to be written within the
* destination <code>BufferedImage</code> will start at this
* offset and have a width and height determined by the source
* region of interest, the subsampling parameters, and the
* destination bounds.
*
* <p> Normal writes are not affected by this method, only writes
* performed using <code>ImageWriter.replacePixels</code>. For
* such writes, the offset specified is within the output stream
* image whose pixels are being modified.
*
* <p> There is no <code>unsetDestinationOffset</code> method;
* simply call <code>setDestinationOffset(new Point(0, 0))</code> to
* restore default values.
*
* @param destinationOffset the offset in the destination, as a
* <code>Point</code>.
*
* @exception IllegalArgumentException if
* <code>destinationOffset</code> is <code>null</code>.
*
* @see #getDestinationOffset
* @see ImageWriter#replacePixels
*/
public void setDestinationOffset(Point destinationOffset) {
if (destinationOffset == null) {
throw new IllegalArgumentException("destinationOffset == null!");
}
this.destinationOffset = (Point)destinationOffset.clone();
}
/** {@collect.stats}
* Returns the offset in the destination image at which pixels are
* to be placed.
*
* <p> If <code>setDestinationOffsets</code> has not been called,
* a <code>Point</code> with zero X and Y values is returned
* (which is the correct value).
*
* @return the destination offset as a <code>Point</code>.
*
* @see #setDestinationOffset
*/
public Point getDestinationOffset() {
return (Point)destinationOffset.clone();
}
/** {@collect.stats}
* Sets the <code>IIOParamController</code> to be used
* to provide settings for this <code>IIOParam</code>
* object when the <code>activateController</code> method
* is called, overriding any default controller. If the
* argument is <code>null</code>, no controller will be
* used, including any default. To restore the default, use
* <code>setController(getDefaultController())</code>.
*
* @param controller An appropriate
* <code>IIOParamController</code>, or <code>null</code>.
*
* @see IIOParamController
* @see #getController
* @see #getDefaultController
* @see #hasController
* @see #activateController()
*/
public void setController(IIOParamController controller) {
this.controller = controller;
}
/** {@collect.stats}
* Returns whatever <code>IIOParamController</code> is currently
* installed. This could be the default if there is one,
* <code>null</code>, or the argument of the most recent call
* to <code>setController</code>.
*
* @return the currently installed
* <code>IIOParamController</code>, or <code>null</code>.
*
* @see IIOParamController
* @see #setController
* @see #getDefaultController
* @see #hasController
* @see #activateController()
*/
public IIOParamController getController() {
return controller;
}
/** {@collect.stats}
* Returns the default <code>IIOParamController</code>, if there
* is one, regardless of the currently installed controller. If
* there is no default controller, returns <code>null</code>.
*
* @return the default <code>IIOParamController</code>, or
* <code>null</code>.
*
* @see IIOParamController
* @see #setController(IIOParamController)
* @see #getController
* @see #hasController
* @see #activateController()
*/
public IIOParamController getDefaultController() {
return defaultController;
}
/** {@collect.stats}
* Returns <code>true</code> if there is a controller installed
* for this <code>IIOParam</code> object. This will return
* <code>true</code> if <code>getController</code> would not
* return <code>null</code>.
*
* @return <code>true</code> if a controller is installed.
*
* @see IIOParamController
* @see #setController(IIOParamController)
* @see #getController
* @see #getDefaultController
* @see #activateController()
*/
public boolean hasController() {
return (controller != null);
}
/** {@collect.stats}
* Activates the installed <code>IIOParamController</code> for
* this <code>IIOParam</code> object and returns the resulting
* value. When this method returns <code>true</code>, all values
* for this <code>IIOParam</code> object will be ready for the
* next read or write operation. If <code>false</code> is
* returned, no settings in this object will have been disturbed
* (<i>i.e.</i>, the user canceled the operation).
*
* <p> Ordinarily, the controller will be a GUI providing a user
* interface for a subclass of <code>IIOParam</code> for a
* particular plug-in. Controllers need not be GUIs, however.
*
* @return <code>true</code> if the controller completed normally.
*
* @exception IllegalStateException if there is no controller
* currently installed.
*
* @see IIOParamController
* @see #setController(IIOParamController)
* @see #getController
* @see #getDefaultController
* @see #hasController
*/
public boolean activateController() {
if (!hasController()) {
throw new IllegalStateException("hasController() == false!");
}
return getController().activate(this);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.color.ColorSpace;
import java.awt.image.IndexColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DirectColorModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.util.Hashtable;
/** {@collect.stats}
* A class that allows the format of an image (in particular, its
* <code>SampleModel</code> and <code>ColorModel</code>) to be
* specified in a convenient manner.
*
*/
public class ImageTypeSpecifier {
/** {@collect.stats}
* The <code>ColorModel</code> to be used as a prototype.
*/
protected ColorModel colorModel;
/** {@collect.stats}
* A <code>SampleModel</code> to be used as a prototype.
*/
protected SampleModel sampleModel;
/** {@collect.stats}
* Cached specifiers for all of the standard
* <code>BufferedImage</code> types.
*/
private static ImageTypeSpecifier[] BISpecifier;
// Initialize the standard specifiers
static {
ColorSpace sRGB = ColorSpace.getInstance(ColorSpace.CS_sRGB);
BISpecifier =
new ImageTypeSpecifier[BufferedImage.TYPE_BYTE_INDEXED + 1];
BISpecifier[BufferedImage.TYPE_CUSTOM] = null;
BISpecifier[BufferedImage.TYPE_INT_RGB] =
createPacked(sRGB,
0x00ff0000,
0x0000ff00,
0x000000ff,
0x0,
DataBuffer.TYPE_INT,
false);
BISpecifier[BufferedImage.TYPE_INT_ARGB] =
createPacked(sRGB,
0x00ff0000,
0x0000ff00,
0x000000ff,
0xff000000,
DataBuffer.TYPE_INT,
false);
BISpecifier[BufferedImage.TYPE_INT_ARGB_PRE] =
createPacked(sRGB,
0x00ff0000,
0x0000ff00,
0x000000ff,
0xff000000,
DataBuffer.TYPE_INT,
true);
BISpecifier[BufferedImage.TYPE_INT_BGR] =
createPacked(sRGB,
0x000000ff,
0x0000ff00,
0x00ff0000,
0x0,
DataBuffer.TYPE_INT,
false);
int[] bOffsRGB = { 2, 1, 0 };
BISpecifier[BufferedImage.TYPE_3BYTE_BGR] =
createInterleaved(sRGB,
bOffsRGB,
DataBuffer.TYPE_BYTE,
false,
false);
int[] bOffsABGR = { 3, 2, 1, 0 };
BISpecifier[BufferedImage.TYPE_4BYTE_ABGR] =
createInterleaved(sRGB,
bOffsABGR,
DataBuffer.TYPE_BYTE,
true,
false);
BISpecifier[BufferedImage.TYPE_4BYTE_ABGR_PRE] =
createInterleaved(sRGB,
bOffsABGR,
DataBuffer.TYPE_BYTE,
true,
true);
BISpecifier[BufferedImage.TYPE_USHORT_565_RGB] =
createPacked(sRGB,
0xF800,
0x07E0,
0x001F,
0x0,
DataBuffer.TYPE_USHORT,
false);
BISpecifier[BufferedImage.TYPE_USHORT_555_RGB] =
createPacked(sRGB,
0x7C00,
0x03E0,
0x001F,
0x0,
DataBuffer.TYPE_USHORT,
false);
BISpecifier[BufferedImage.TYPE_BYTE_GRAY] =
createGrayscale(8,
DataBuffer.TYPE_BYTE,
false);
BISpecifier[BufferedImage.TYPE_USHORT_GRAY] =
createGrayscale(16,
DataBuffer.TYPE_USHORT,
false);
BISpecifier[BufferedImage.TYPE_BYTE_BINARY] =
createGrayscale(1,
DataBuffer.TYPE_BYTE,
false);
BufferedImage bi =
new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_INDEXED);
IndexColorModel icm = (IndexColorModel)bi.getColorModel();
int mapSize = icm.getMapSize();
byte[] redLUT = new byte[mapSize];
byte[] greenLUT = new byte[mapSize];
byte[] blueLUT = new byte[mapSize];
byte[] alphaLUT = new byte[mapSize];
icm.getReds(redLUT);
icm.getGreens(greenLUT);
icm.getBlues(blueLUT);
icm.getAlphas(alphaLUT);
BISpecifier[BufferedImage.TYPE_BYTE_INDEXED] =
createIndexed(redLUT, greenLUT, blueLUT, alphaLUT,
8,
DataBuffer.TYPE_BYTE);
}
/** {@collect.stats}
* A constructor to be used by inner subclasses only.
*/
private ImageTypeSpecifier() {}
/** {@collect.stats}
* Constructs an <code>ImageTypeSpecifier</code> directly
* from a <code>ColorModel</code> and a <code>SampleModel</code>.
* It is the caller's responsibility to supply compatible
* parameters.
*
* @param colorModel a <code>ColorModel</code>.
* @param sampleModel a <code>SampleModel</code>.
*
* @exception IllegalArgumentException if either parameter is
* <code>null</code>.
* @exception IllegalArgumentException if <code>sampleModel</code>
* is not compatible with <code>colorModel</code>.
*/
public ImageTypeSpecifier(ColorModel colorModel, SampleModel sampleModel) {
if (colorModel == null) {
throw new IllegalArgumentException("colorModel == null!");
}
if (sampleModel == null) {
throw new IllegalArgumentException("sampleModel == null!");
}
if (!colorModel.isCompatibleSampleModel(sampleModel)) {
throw new IllegalArgumentException
("sampleModel is incompatible with colorModel!");
}
this.colorModel = colorModel;
this.sampleModel = sampleModel;
}
/** {@collect.stats}
* Constructs an <code>ImageTypeSpecifier</code> from a
* <code>RenderedImage</code>. If a <code>BufferedImage</code> is
* being used, one of the factory methods
* <code>createFromRenderedImage</code> or
* <code>createFromBufferedImageType</code> should be used instead in
* order to get a more accurate result.
*
* @param image a <code>RenderedImage</code>.
*
* @exception IllegalArgumentException if the argument is
* <code>null</code>.
*/
public ImageTypeSpecifier(RenderedImage image) {
if (image == null) {
throw new IllegalArgumentException("image == null!");
}
colorModel = image.getColorModel();
sampleModel = image.getSampleModel();
}
// Packed
static class Packed extends ImageTypeSpecifier {
ColorSpace colorSpace;
int redMask;
int greenMask;
int blueMask;
int alphaMask;
int transferType;
boolean isAlphaPremultiplied;
public Packed(ColorSpace colorSpace,
int redMask,
int greenMask,
int blueMask,
int alphaMask, // 0 if no alpha
int transferType,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (colorSpace.getType() != ColorSpace.TYPE_RGB) {
throw new IllegalArgumentException
("colorSpace is not of type TYPE_RGB!");
}
if (transferType != DataBuffer.TYPE_BYTE &&
transferType != DataBuffer.TYPE_USHORT &&
transferType != DataBuffer.TYPE_INT) {
throw new IllegalArgumentException
("Bad value for transferType!");
}
if (redMask == 0 && greenMask == 0 &&
blueMask == 0 && alphaMask == 0) {
throw new IllegalArgumentException
("No mask has at least 1 bit set!");
}
this.colorSpace = colorSpace;
this.redMask = redMask;
this.greenMask = greenMask;
this.blueMask = blueMask;
this.alphaMask = alphaMask;
this.transferType = transferType;
this.isAlphaPremultiplied = isAlphaPremultiplied;
int bits = 32;
this.colorModel =
new DirectColorModel(colorSpace,
bits,
redMask, greenMask, blueMask,
alphaMask, isAlphaPremultiplied,
transferType);
this.sampleModel = colorModel.createCompatibleSampleModel(1, 1);
}
}
/** {@collect.stats}
* Returns a specifier for a packed image format that will use a
* <code>DirectColorModel</code> and a packed
* <code>SampleModel</code> to store each pixel packed into in a
* single byte, short, or int.
*
* @param colorSpace the desired <code>ColorSpace</code>.
* @param redMask a contiguous mask indicated the position of the
* red channel.
* @param greenMask a contiguous mask indicated the position of the
* green channel.
* @param blueMask a contiguous mask indicated the position of the
* blue channel.
* @param alphaMask a contiguous mask indicated the position of the
* alpha channel.
* @param transferType the desired <code>SampleModel</code> transfer type.
* @param isAlphaPremultiplied <code>true</code> if the color channels
* will be premultipled by the alpha channel.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>colorSpace</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>colorSpace</code>
* is not of type <code>TYPE_RGB</code>.
* @exception IllegalArgumentException if no mask has at least 1
* bit set.
* @exception IllegalArgumentException if
* <code>transferType</code> if not one of
* <code>DataBuffer.TYPE_BYTE</code>,
* <code>DataBuffer.TYPE_USHORT</code>, or
* <code>DataBuffer.TYPE_INT</code>.
*/
public static ImageTypeSpecifier
createPacked(ColorSpace colorSpace,
int redMask,
int greenMask,
int blueMask,
int alphaMask, // 0 if no alpha
int transferType,
boolean isAlphaPremultiplied) {
return new ImageTypeSpecifier.Packed(colorSpace,
redMask,
greenMask,
blueMask,
alphaMask, // 0 if no alpha
transferType,
isAlphaPremultiplied);
}
static ColorModel createComponentCM(ColorSpace colorSpace,
int numBands,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
int transparency =
hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE;
int[] numBits = new int[numBands];
int bits = DataBuffer.getDataTypeSize(dataType);
for (int i = 0; i < numBands; i++) {
numBits[i] = bits;
}
return new ComponentColorModel(colorSpace,
numBits,
hasAlpha,
isAlphaPremultiplied,
transparency,
dataType);
}
// Interleaved
static class Interleaved extends ImageTypeSpecifier {
ColorSpace colorSpace;
int[] bandOffsets;
int dataType;
boolean hasAlpha;
boolean isAlphaPremultiplied;
public Interleaved(ColorSpace colorSpace,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (bandOffsets == null) {
throw new IllegalArgumentException("bandOffsets == null!");
}
int numBands = colorSpace.getNumComponents() +
(hasAlpha ? 1 : 0);
if (bandOffsets.length != numBands) {
throw new IllegalArgumentException
("bandOffsets.length is wrong!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT &&
dataType != DataBuffer.TYPE_INT &&
dataType != DataBuffer.TYPE_FLOAT &&
dataType != DataBuffer.TYPE_DOUBLE) {
throw new IllegalArgumentException
("Bad value for dataType!");
}
this.colorSpace = colorSpace;
this.bandOffsets = (int[])bandOffsets.clone();
this.dataType = dataType;
this.hasAlpha = hasAlpha;
this.isAlphaPremultiplied = isAlphaPremultiplied;
this.colorModel =
ImageTypeSpecifier.createComponentCM(colorSpace,
bandOffsets.length,
dataType,
hasAlpha,
isAlphaPremultiplied);
int minBandOffset = bandOffsets[0];
int maxBandOffset = minBandOffset;
for (int i = 0; i < bandOffsets.length; i++) {
int offset = bandOffsets[i];
minBandOffset = Math.min(offset, minBandOffset);
maxBandOffset = Math.max(offset, maxBandOffset);
}
int pixelStride = maxBandOffset - minBandOffset + 1;
int w = 1;
int h = 1;
this.sampleModel =
new PixelInterleavedSampleModel(dataType,
w, h,
pixelStride,
w*pixelStride,
bandOffsets);
}
public boolean equals(Object o) {
if ((o == null) ||
!(o instanceof ImageTypeSpecifier.Interleaved)) {
return false;
}
ImageTypeSpecifier.Interleaved that =
(ImageTypeSpecifier.Interleaved)o;
if ((!(this.colorSpace.equals(that.colorSpace))) ||
(this.dataType != that.dataType) ||
(this.hasAlpha != that.hasAlpha) ||
(this.isAlphaPremultiplied != that.isAlphaPremultiplied) ||
(this.bandOffsets.length != that.bandOffsets.length)) {
return false;
}
for (int i = 0; i < bandOffsets.length; i++) {
if (this.bandOffsets[i] != that.bandOffsets[i]) {
return false;
}
}
return true;
}
public int hashCode() {
return (super.hashCode() +
(4 * bandOffsets.length) +
(25 * dataType) +
(hasAlpha ? 17 : 18));
}
}
/** {@collect.stats}
* Returns a specifier for an interleaved image format that will
* use a <code>ComponentColorModel</code> and a
* <code>PixelInterleavedSampleModel</code> to store each pixel
* component in a separate byte, short, or int.
*
* @param colorSpace the desired <code>ColorSpace</code>.
* @param bandOffsets an array of <code>int</code>s indicating the
* offsets for each band.
* @param dataType the desired data type, as one of the enumerations
* from the <code>DataBuffer</code> class.
* @param hasAlpha <code>true</code> if an alpha channel is desired.
* @param isAlphaPremultiplied <code>true</code> if the color channels
* will be premultipled by the alpha channel.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>colorSpace</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>bandOffsets</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the legal <code>DataBuffer.TYPE_*</code> constants.
* @exception IllegalArgumentException if
* <code>bandOffsets.length</code> does not equal the number of
* color space components, plus 1 if <code>hasAlpha</code> is
* <code>true</code>.
*/
public static ImageTypeSpecifier
createInterleaved(ColorSpace colorSpace,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
return new ImageTypeSpecifier.Interleaved(colorSpace,
bandOffsets,
dataType,
hasAlpha,
isAlphaPremultiplied);
}
// Banded
static class Banded extends ImageTypeSpecifier {
ColorSpace colorSpace;
int[] bankIndices;
int[] bandOffsets;
int dataType;
boolean hasAlpha;
boolean isAlphaPremultiplied;
public Banded(ColorSpace colorSpace,
int[] bankIndices,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
if (colorSpace == null) {
throw new IllegalArgumentException("colorSpace == null!");
}
if (bankIndices == null) {
throw new IllegalArgumentException("bankIndices == null!");
}
if (bandOffsets == null) {
throw new IllegalArgumentException("bandOffsets == null!");
}
if (bankIndices.length != bandOffsets.length) {
throw new IllegalArgumentException
("bankIndices.length != bandOffsets.length!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT &&
dataType != DataBuffer.TYPE_INT &&
dataType != DataBuffer.TYPE_FLOAT &&
dataType != DataBuffer.TYPE_DOUBLE) {
throw new IllegalArgumentException
("Bad value for dataType!");
}
int numBands = colorSpace.getNumComponents() +
(hasAlpha ? 1 : 0);
if (bandOffsets.length != numBands) {
throw new IllegalArgumentException
("bandOffsets.length is wrong!");
}
this.colorSpace = colorSpace;
this.bankIndices = (int[])bankIndices.clone();
this.bandOffsets = (int[])bandOffsets.clone();
this.dataType = dataType;
this.hasAlpha = hasAlpha;
this.isAlphaPremultiplied = isAlphaPremultiplied;
this.colorModel =
ImageTypeSpecifier.createComponentCM(colorSpace,
bankIndices.length,
dataType,
hasAlpha,
isAlphaPremultiplied);
int w = 1;
int h = 1;
this.sampleModel = new BandedSampleModel(dataType,
w, h,
w,
bankIndices,
bandOffsets);
}
public boolean equals(Object o) {
if ((o == null) ||
!(o instanceof ImageTypeSpecifier.Banded)) {
return false;
}
ImageTypeSpecifier.Banded that =
(ImageTypeSpecifier.Banded)o;
if ((!(this.colorSpace.equals(that.colorSpace))) ||
(this.dataType != that.dataType) ||
(this.hasAlpha != that.hasAlpha) ||
(this.isAlphaPremultiplied != that.isAlphaPremultiplied) ||
(this.bankIndices.length != that.bankIndices.length) ||
(this.bandOffsets.length != that.bandOffsets.length)) {
return false;
}
for (int i = 0; i < bankIndices.length; i++) {
if (this.bankIndices[i] != that.bankIndices[i]) {
return false;
}
}
for (int i = 0; i < bandOffsets.length; i++) {
if (this.bandOffsets[i] != that.bandOffsets[i]) {
return false;
}
}
return true;
}
public int hashCode() {
return (super.hashCode() +
(3 * bandOffsets.length) +
(7 * bankIndices.length) +
(21 * dataType) +
(hasAlpha ? 19 : 29));
}
}
/** {@collect.stats}
* Returns a specifier for a banded image format that will use a
* <code>ComponentColorModel</code> and a
* <code>BandedSampleModel</code> to store each channel in a
* separate array.
*
* @param colorSpace the desired <code>ColorSpace</code>.
* @param bankIndices an array of <code>int</code>s indicating the
* bank in which each band will be stored.
* @param bandOffsets an array of <code>int</code>s indicating the
* starting offset of each band within its bank.
* @param dataType the desired data type, as one of the enumerations
* from the <code>DataBuffer</code> class.
* @param hasAlpha <code>true</code> if an alpha channel is desired.
* @param isAlphaPremultiplied <code>true</code> if the color channels
* will be premultipled by the alpha channel.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>colorSpace</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>bankIndices</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>bandOffsets</code>
* is <code>null</code>.
* @exception IllegalArgumentException if the lengths of
* <code>bankIndices</code> and <code>bandOffsets</code> differ.
* @exception IllegalArgumentException if
* <code>bandOffsets.length</code> does not equal the number of
* color space components, plus 1 if <code>hasAlpha</code> is
* <code>true</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of the legal <code>DataBuffer.TYPE_*</code> constants.
*/
public static ImageTypeSpecifier
createBanded(ColorSpace colorSpace,
int[] bankIndices,
int[] bandOffsets,
int dataType,
boolean hasAlpha,
boolean isAlphaPremultiplied) {
return new ImageTypeSpecifier.Banded(colorSpace,
bankIndices,
bandOffsets,
dataType,
hasAlpha,
isAlphaPremultiplied);
}
// Grayscale
static class Grayscale extends ImageTypeSpecifier {
int bits;
int dataType;
boolean isSigned;
boolean hasAlpha;
boolean isAlphaPremultiplied;
public Grayscale(int bits,
int dataType,
boolean isSigned,
boolean hasAlpha,
boolean isAlphaPremultiplied)
{
if (bits != 1 && bits != 2 && bits != 4 &&
bits != 8 && bits != 16)
{
throw new IllegalArgumentException("Bad value for bits!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT)
{
throw new IllegalArgumentException
("Bad value for dataType!");
}
if (bits > 8 && dataType == DataBuffer.TYPE_BYTE) {
throw new IllegalArgumentException
("Too many bits for dataType!");
}
this.bits = bits;
this.dataType = dataType;
this.isSigned = isSigned;
this.hasAlpha = hasAlpha;
this.isAlphaPremultiplied = isAlphaPremultiplied;
ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
if ((bits == 8 && dataType == DataBuffer.TYPE_BYTE) ||
(bits == 16 &&
(dataType == DataBuffer.TYPE_SHORT ||
dataType == DataBuffer.TYPE_USHORT))) {
// Use component color model & sample model
int numBands = hasAlpha ? 2 : 1;
int transparency =
hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE;
int[] nBits = new int[numBands];
nBits[0] = bits;
if (numBands == 2) {
nBits[1] = bits;
}
this.colorModel =
new ComponentColorModel(colorSpace,
nBits,
hasAlpha,
isAlphaPremultiplied,
transparency,
dataType);
int[] bandOffsets = new int[numBands];
bandOffsets[0] = 0;
if (numBands == 2) {
bandOffsets[1] = 1;
}
int w = 1;
int h = 1;
this.sampleModel =
new PixelInterleavedSampleModel(dataType,
w, h,
numBands, w*numBands,
bandOffsets);
} else {
int numEntries = 1 << bits;
byte[] arr = new byte[numEntries];
for (int i = 0; i < numEntries; i++) {
arr[i] = (byte)(i*255/(numEntries - 1));
}
this.colorModel =
new IndexColorModel(bits, numEntries, arr, arr, arr);
this.sampleModel =
new MultiPixelPackedSampleModel(dataType, 1, 1, bits);
}
}
}
/** {@collect.stats}
* Returns a specifier for a grayscale image format that will pack
* pixels of the given bit depth into array elements of
* the specified data type.
*
* @param bits the number of bits per gray value (1, 2, 4, 8, or 16).
* @param dataType the desired data type, as one of the enumerations
* from the <code>DataBuffer</code> class.
* @param isSigned <code>true</code> if negative values are to
* be represented.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>bits</code> is
* not one of 1, 2, 4, 8, or 16.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of <code>DataBuffer.TYPE_BYTE</code>,
* <code>DataBuffer.TYPE_SHORT</code>, or
* <code>DataBuffer.TYPE_USHORT</code>.
* @exception IllegalArgumentException if <code>bits</code> is
* larger than the bit size of the given <code>dataType</code>.
*/
public static ImageTypeSpecifier
createGrayscale(int bits,
int dataType,
boolean isSigned) {
return new ImageTypeSpecifier.Grayscale(bits,
dataType,
isSigned,
false,
false);
}
/** {@collect.stats}
* Returns a specifier for a grayscale plus alpha image format
* that will pack pixels of the given bit depth into array
* elements of the specified data type.
*
* @param bits the number of bits per gray value (1, 2, 4, 8, or 16).
* @param dataType the desired data type, as one of the enumerations
* from the <code>DataBuffer</code> class.
* @param isSigned <code>true</code> if negative values are to
* be represented.
* @param isAlphaPremultiplied <code>true</code> if the luminance channel
* will be premultipled by the alpha channel.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>bits</code> is
* not one of 1, 2, 4, 8, or 16.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of <code>DataBuffer.TYPE_BYTE</code>,
* <code>DataBuffer.TYPE_SHORT</code>, or
* <code>DataBuffer.TYPE_USHORT</code>.
* @exception IllegalArgumentException if <code>bits</code> is
* larger than the bit size of the given <code>dataType</code>.
*/
public static ImageTypeSpecifier
createGrayscale(int bits,
int dataType,
boolean isSigned,
boolean isAlphaPremultiplied) {
return new ImageTypeSpecifier.Grayscale(bits,
dataType,
isSigned,
true,
isAlphaPremultiplied);
}
// Indexed
static class Indexed extends ImageTypeSpecifier {
byte[] redLUT;
byte[] greenLUT;
byte[] blueLUT;
byte[] alphaLUT = null;
int bits;
int dataType;
public Indexed(byte[] redLUT,
byte[] greenLUT,
byte[] blueLUT,
byte[] alphaLUT,
int bits,
int dataType) {
if (redLUT == null || greenLUT == null || blueLUT == null) {
throw new IllegalArgumentException("LUT is null!");
}
if (bits != 1 && bits != 2 && bits != 4 &&
bits != 8 && bits != 16) {
throw new IllegalArgumentException("Bad value for bits!");
}
if (dataType != DataBuffer.TYPE_BYTE &&
dataType != DataBuffer.TYPE_SHORT &&
dataType != DataBuffer.TYPE_USHORT &&
dataType != DataBuffer.TYPE_INT) {
throw new IllegalArgumentException
("Bad value for dataType!");
}
if ((bits > 8 && dataType == DataBuffer.TYPE_BYTE) ||
(bits > 16 && dataType != DataBuffer.TYPE_INT)) {
throw new IllegalArgumentException
("Too many bits for dataType!");
}
int len = 1 << bits;
if (redLUT.length != len ||
greenLUT.length != len ||
blueLUT.length != len ||
(alphaLUT != null && alphaLUT.length != len)) {
throw new IllegalArgumentException("LUT has improper length!");
}
this.redLUT = (byte[])redLUT.clone();
this.greenLUT = (byte[])greenLUT.clone();
this.blueLUT = (byte[])blueLUT.clone();
if (alphaLUT != null) {
this.alphaLUT = (byte[])alphaLUT.clone();
}
this.bits = bits;
this.dataType = dataType;
if (alphaLUT == null) {
this.colorModel = new IndexColorModel(bits,
redLUT.length,
redLUT,
greenLUT,
blueLUT);
} else {
this.colorModel = new IndexColorModel(bits,
redLUT.length,
redLUT,
greenLUT,
blueLUT,
alphaLUT);
}
if ((bits == 8 && dataType == DataBuffer.TYPE_BYTE) ||
(bits == 16 &&
(dataType == DataBuffer.TYPE_SHORT ||
dataType == DataBuffer.TYPE_USHORT))) {
int[] bandOffsets = { 0 };
this.sampleModel =
new PixelInterleavedSampleModel(dataType,
1, 1, 1, 1,
bandOffsets);
} else {
this.sampleModel =
new MultiPixelPackedSampleModel(dataType, 1, 1, bits);
}
}
}
/** {@collect.stats}
* Returns a specifier for an indexed-color image format that will pack
* index values of the given bit depth into array elements of
* the specified data type.
*
* @param redLUT an array of <code>byte</code>s containing
* the red values for each index.
* @param greenLUT an array of <code>byte</code>s containing * the
* green values for each index.
* @param blueLUT an array of <code>byte</code>s containing the
* blue values for each index.
* @param alphaLUT an array of <code>byte</code>s containing the
* alpha values for each index, or <code>null</code> to create a
* fully opaque LUT.
* @param bits the number of bits in each index.
* @param dataType the desired output type, as one of the enumerations
* from the <code>DataBuffer</code> class.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>redLUT</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>greenLUT</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>blueLUT</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>bits</code> is
* not one of 1, 2, 4, 8, or 16.
* @exception IllegalArgumentException if the
* non-<code>null</code> LUT parameters do not have lengths of
* exactly <code>1 << bits</code>.
* @exception IllegalArgumentException if <code>dataType</code> is
* not one of <code>DataBuffer.TYPE_BYTE</code>,
* <code>DataBuffer.TYPE_SHORT</code>,
* <code>DataBuffer.TYPE_USHORT</code>,
* or <code>DataBuffer.TYPE_INT</code>.
* @exception IllegalArgumentException if <code>bits</code> is
* larger than the bit size of the given <code>dataType</code>.
*/
public static ImageTypeSpecifier
createIndexed(byte[] redLUT,
byte[] greenLUT,
byte[] blueLUT,
byte[] alphaLUT,
int bits,
int dataType) {
return new ImageTypeSpecifier.Indexed(redLUT,
greenLUT,
blueLUT,
alphaLUT,
bits,
dataType);
}
/** {@collect.stats}
* Returns an <code>ImageTypeSpecifier</code> that encodes
* one of the standard <code>BufferedImage</code> types
* (other than <code>TYPE_CUSTOM</code>).
*
* @param bufferedImageType an int representing one of the standard
* <code>BufferedImage</code> types.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if
* <code>bufferedImageType</code> is not one of the standard
* types, or is equal to <code>TYPE_CUSTOM</code>.
*
* @see java.awt.image.BufferedImage
* @see java.awt.image.BufferedImage#TYPE_INT_RGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB_PRE
* @see java.awt.image.BufferedImage#TYPE_INT_BGR
* @see java.awt.image.BufferedImage#TYPE_3BYTE_BGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR_PRE
* @see java.awt.image.BufferedImage#TYPE_USHORT_565_RGB
* @see java.awt.image.BufferedImage#TYPE_USHORT_555_RGB
* @see java.awt.image.BufferedImage#TYPE_BYTE_GRAY
* @see java.awt.image.BufferedImage#TYPE_USHORT_GRAY
* @see java.awt.image.BufferedImage#TYPE_BYTE_BINARY
* @see java.awt.image.BufferedImage#TYPE_BYTE_INDEXED
*/
public static
ImageTypeSpecifier createFromBufferedImageType(int bufferedImageType) {
if (bufferedImageType >= BufferedImage.TYPE_INT_RGB &&
bufferedImageType <= BufferedImage.TYPE_BYTE_INDEXED) {
return BISpecifier[bufferedImageType];
} else if (bufferedImageType == BufferedImage.TYPE_CUSTOM) {
throw new IllegalArgumentException("Cannot create from TYPE_CUSTOM!");
} else {
throw new IllegalArgumentException("Invalid BufferedImage type!");
}
}
/** {@collect.stats}
* Returns an <code>ImageTypeSpecifier</code> that encodes the
* layout of a <code>RenderedImage</code> (which may be a
* <code>BufferedImage</code>).
*
* @param image a <code>RenderedImage</code>.
*
* @return an <code>ImageTypeSpecifier</code> with the desired
* characteristics.
*
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
*/
public static
ImageTypeSpecifier createFromRenderedImage(RenderedImage image) {
if (image == null) {
throw new IllegalArgumentException("image == null!");
}
if (image instanceof BufferedImage) {
int bufferedImageType = ((BufferedImage)image).getType();
if (bufferedImageType != BufferedImage.TYPE_CUSTOM) {
return BISpecifier[bufferedImageType];
}
}
return new ImageTypeSpecifier(image);
}
/** {@collect.stats}
* Returns an int containing one of the enumerated constant values
* describing image formats from <code>BufferedImage</code>.
*
* @return an <code>int</code> representing a
* <code>BufferedImage</code> type.
*
* @see java.awt.image.BufferedImage
* @see java.awt.image.BufferedImage#TYPE_CUSTOM
* @see java.awt.image.BufferedImage#TYPE_INT_RGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB
* @see java.awt.image.BufferedImage#TYPE_INT_ARGB_PRE
* @see java.awt.image.BufferedImage#TYPE_INT_BGR
* @see java.awt.image.BufferedImage#TYPE_3BYTE_BGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR
* @see java.awt.image.BufferedImage#TYPE_4BYTE_ABGR_PRE
* @see java.awt.image.BufferedImage#TYPE_USHORT_565_RGB
* @see java.awt.image.BufferedImage#TYPE_USHORT_555_RGB
* @see java.awt.image.BufferedImage#TYPE_BYTE_GRAY
* @see java.awt.image.BufferedImage#TYPE_USHORT_GRAY
* @see java.awt.image.BufferedImage#TYPE_BYTE_BINARY
* @see java.awt.image.BufferedImage#TYPE_BYTE_INDEXED
*/
public int getBufferedImageType() {
BufferedImage bi = createBufferedImage(1, 1);
return bi.getType();
}
/** {@collect.stats}
* Return the number of color components
* specified by this object. This is the same value as returned by
* <code>ColorModel.getNumComponents</code>
*
* @return the number of components in the image.
*/
public int getNumComponents() {
return colorModel.getNumComponents();
}
/** {@collect.stats}
* Return the number of bands
* specified by this object. This is the same value as returned by
* <code>SampleModel.getNumBands</code>
*
* @return the number of bands in the image.
*/
public int getNumBands() {
return sampleModel.getNumBands();
}
/** {@collect.stats}
* Return the number of bits used to represent samples of the given band.
*
* @param band the index of the band to be queried, as an
* int.
*
* @return an int specifying a number of bits.
*
* @exception IllegalArgumentException if <code>band</code> is
* negative or greater than the largest band index.
*/
public int getBitsPerBand(int band) {
if (band < 0 | band >= getNumBands()) {
throw new IllegalArgumentException("band out of range!");
}
return sampleModel.getSampleSize(band);
}
/** {@collect.stats}
* Returns a <code>SampleModel</code> based on the settings
* encapsulated within this object. The width and height of the
* <code>SampleModel</code> will be set to arbitrary values.
*
* @return a <code>SampleModel</code> with arbitrary dimensions.
*/
public SampleModel getSampleModel() {
return sampleModel;
}
/** {@collect.stats}
* Returns a <code>SampleModel</code> based on the settings
* encapsulated within this object. The width and height of the
* <code>SampleModel</code> will be set to the supplied values.
*
* @param width the desired width of the returned <code>SampleModel</code>.
* @param height the desired height of the returned
* <code>SampleModel</code>.
*
* @return a <code>SampleModel</code> with the given dimensions.
*
* @exception IllegalArgumentException if either <code>width</code> or
* <code>height</code> are negative or zero.
* @exception IllegalArgumentException if the product of
* <code>width</code> and <code>height</code> is greater than
* <code>Integer.MAX_VALUE</code>
*/
public SampleModel getSampleModel(int width, int height) {
if ((long)width*height > Integer.MAX_VALUE) {
throw new IllegalArgumentException
("width*height > Integer.MAX_VALUE!");
}
return sampleModel.createCompatibleSampleModel(width, height);
}
/** {@collect.stats}
* Returns the <code>ColorModel</code> specified by this object.
*
* @return a <code>ColorModel</code>.
*/
public ColorModel getColorModel() {
return colorModel;
}
/** {@collect.stats}
* Creates a <code>BufferedImage</code> with a given width and
* height according to the specification embodied in this object.
*
* @param width the desired width of the returned
* <code>BufferedImage</code>.
* @param height the desired height of the returned
* <code>BufferedImage</code>.
*
* @return a new <code>BufferedImage</code>
*
* @exception IllegalArgumentException if either <code>width</code> or
* <code>height</code> are negative or zero.
* @exception IllegalArgumentException if the product of
* <code>width</code> and <code>height</code> is greater than
* <code>Integer.MAX_VALUE</code>, or if the number of array
* elements needed to store the image is greater than
* <code>Integer.MAX_VALUE</code>.
*/
public BufferedImage createBufferedImage(int width, int height) {
try {
SampleModel sampleModel = getSampleModel(width, height);
WritableRaster raster =
Raster.createWritableRaster(sampleModel,
new Point(0, 0));
return new BufferedImage(colorModel, raster,
colorModel.isAlphaPremultiplied(),
new Hashtable());
} catch (NegativeArraySizeException e) {
// Exception most likely thrown from a DataBuffer constructor
throw new IllegalArgumentException
("Array size > Integer.MAX_VALUE!");
}
}
/** {@collect.stats}
* Returns <code>true</code> if the given <code>Object</code> is
* an <code>ImageTypeSpecifier</code> and has a
* <code>SampleModel</code> and <code>ColorModel</code> that are
* equal to those of this object.
*
* @param o the <code>Object</code> to be compared for equality.
*
* @return <code>true</code> if the given object is an equivalent
* <code>ImageTypeSpecifier</code>.
*/
public boolean equals(Object o) {
if ((o == null) || !(o instanceof ImageTypeSpecifier)) {
return false;
}
ImageTypeSpecifier that = (ImageTypeSpecifier)o;
return (colorModel.equals(that.colorModel)) &&
(sampleModel.equals(that.sampleModel));
}
/** {@collect.stats}
* Returns the hash code for this ImageTypeSpecifier.
*
* @return a hash code for this ImageTypeSpecifier
*/
public int hashCode() {
return (9 * colorModel.hashCode()) + (14 * sampleModel.hashCode());
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.util.List;
import javax.imageio.metadata.IIOMetadata;
/** {@collect.stats}
* A simple container class to aggregate an image, a set of
* thumbnail (preview) images, and an object representing metadata
* associated with the image.
*
* <p> The image data may take the form of either a
* <code>RenderedImage</code>, or a <code>Raster</code>. Reader
* methods that return an <code>IIOImage</code> will always return a
* <code>BufferedImage</code> using the <code>RenderedImage</code>
* reference. Writer methods that accept an <code>IIOImage</code>
* will always accept a <code>RenderedImage</code>, and may optionally
* accept a <code>Raster</code>.
*
* <p> Exactly one of <code>getRenderedImage</code> and
* <code>getRaster</code> will return a non-<code>null</code> value.
* Subclasses are responsible for ensuring this behavior.
*
* @see ImageReader#readAll(int, ImageReadParam)
* @see ImageReader#readAll(java.util.Iterator)
* @see ImageWriter#write(javax.imageio.metadata.IIOMetadata,
* IIOImage, ImageWriteParam)
* @see ImageWriter#write(IIOImage)
* @see ImageWriter#writeToSequence(IIOImage, ImageWriteParam)
* @see ImageWriter#writeInsert(int, IIOImage, ImageWriteParam)
*
*/
public class IIOImage {
/** {@collect.stats}
* The <code>RenderedImage</code> being referenced.
*/
protected RenderedImage image;
/** {@collect.stats}
* The <code>Raster</code> being referenced.
*/
protected Raster raster;
/** {@collect.stats}
* A <code>List</code> of <code>BufferedImage</code> thumbnails,
* or <code>null</code>. Non-<code>BufferedImage</code> objects
* must not be stored in this <code>List</code>.
*/
protected List<? extends BufferedImage> thumbnails = null;
/** {@collect.stats}
* An <code>IIOMetadata</code> object containing metadata
* associated with the image.
*/
protected IIOMetadata metadata;
/** {@collect.stats}
* Constructs an <code>IIOImage</code> containing a
* <code>RenderedImage</code>, and thumbnails and metadata
* associated with it.
*
* <p> All parameters are stored by reference.
*
* <p> The <code>thumbnails</code> argument must either be
* <code>null</code> or contain only <code>BufferedImage</code>
* objects.
*
* @param image a <code>RenderedImage</code>.
* @param thumbnails a <code>List</code> of <code>BufferedImage</code>s,
* or <code>null</code>.
* @param metadata an <code>IIOMetadata</code> object, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
*/
public IIOImage(RenderedImage image,
List<? extends BufferedImage> thumbnails,
IIOMetadata metadata) {
if (image == null) {
throw new IllegalArgumentException("image == null!");
}
this.image = image;
this.raster = null;
this.thumbnails = thumbnails;
this.metadata = metadata;
}
/** {@collect.stats}
* Constructs an <code>IIOImage</code> containing a
* <code>Raster</code>, and thumbnails and metadata
* associated with it.
*
* <p> All parameters are stored by reference.
*
* @param raster a <code>Raster</code>.
* @param thumbnails a <code>List</code> of <code>BufferedImage</code>s,
* or <code>null</code>.
* @param metadata an <code>IIOMetadata</code> object, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>raster</code> is
* <code>null</code>.
*/
public IIOImage(Raster raster,
List<? extends BufferedImage> thumbnails,
IIOMetadata metadata) {
if (raster == null) {
throw new IllegalArgumentException("raster == null!");
}
this.raster = raster;
this.image = null;
this.thumbnails = thumbnails;
this.metadata = metadata;
}
/** {@collect.stats}
* Returns the currently set <code>RenderedImage</code>, or
* <code>null</code> if only a <code>Raster</code> is available.
*
* @return a <code>RenderedImage</code>, or <code>null</code>.
*
* @see #setRenderedImage
*/
public RenderedImage getRenderedImage() {
synchronized(this) {
return image;
}
}
/** {@collect.stats}
* Sets the current <code>RenderedImage</code>. The value is
* stored by reference. Any existing <code>Raster</code> is
* discarded.
*
* @param image a <code>RenderedImage</code>.
*
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
*
* @see #getRenderedImage
*/
public void setRenderedImage(RenderedImage image) {
synchronized(this) {
if (image == null) {
throw new IllegalArgumentException("image == null!");
}
this.image = image;
this.raster = null;
}
}
/** {@collect.stats}
* Returns <code>true</code> if this <code>IIOImage</code> stores
* a <code>Raster</code> rather than a <code>RenderedImage</code>.
*
* @return <code>true</code> if a <code>Raster</code> is
* available.
*/
public boolean hasRaster() {
synchronized(this) {
return (raster != null);
}
}
/** {@collect.stats}
* Returns the currently set <code>Raster</code>, or
* <code>null</code> if only a <code>RenderedImage</code> is
* available.
*
* @return a <code>Raster</code>, or <code>null</code>.
*
* @see #setRaster
*/
public Raster getRaster() {
synchronized(this) {
return raster;
}
}
/** {@collect.stats}
* Sets the current <code>Raster</code>. The value is
* stored by reference. Any existing <code>RenderedImage</code> is
* discarded.
*
* @param raster a <code>Raster</code>.
*
* @exception IllegalArgumentException if <code>raster</code> is
* <code>null</code>.
*
* @see #getRaster
*/
public void setRaster(Raster raster) {
synchronized(this) {
if (raster == null) {
throw new IllegalArgumentException("raster == null!");
}
this.raster = raster;
this.image = null;
}
}
/** {@collect.stats}
* Returns the number of thumbnails stored in this
* <code>IIOImage</code>.
*
* @return the number of thumbnails, as an <code>int</code>.
*/
public int getNumThumbnails() {
return thumbnails == null ? 0 : thumbnails.size();
}
/** {@collect.stats}
* Returns a thumbnail associated with the main image.
*
* @param index the index of the desired thumbnail image.
*
* @return a thumbnail image, as a <code>BufferedImage</code>.
*
* @exception IndexOutOfBoundsException if the supplied index is
* negative or larger than the largest valid index.
* @exception ClassCastException if a
* non-<code>BufferedImage</code> object is encountered in the
* list of thumbnails at the given index.
*
* @see #getThumbnails
* @see #setThumbnails
*/
public BufferedImage getThumbnail(int index) {
if (thumbnails == null) {
throw new IndexOutOfBoundsException("No thumbnails available!");
}
return (BufferedImage)thumbnails.get(index);
}
/** {@collect.stats}
* Returns the current <code>List</code> of thumbnail
* <code>BufferedImage</code>s, or <code>null</code> if none is
* set. A live reference is returned.
*
* @return the current <code>List</code> of
* <code>BufferedImage</code> thumbnails, or <code>null</code>.
*
* @see #getThumbnail(int)
* @see #setThumbnails
*/
public List<? extends BufferedImage> getThumbnails() {
return thumbnails;
}
/** {@collect.stats}
* Sets the list of thumbnails to a new <code>List</code> of
* <code>BufferedImage</code>s, or to <code>null</code>. The
* reference to the previous <code>List</code> is discarded.
*
* <p> The <code>thumbnails</code> argument must either be
* <code>null</code> or contain only <code>BufferedImage</code>
* objects.
*
* @param thumbnails a <code>List</code> of
* <code>BufferedImage</code> thumbnails, or <code>null</code>.
*
* @see #getThumbnail(int)
* @see #getThumbnails
*/
public void setThumbnails(List<? extends BufferedImage> thumbnails) {
this.thumbnails = thumbnails;
}
/** {@collect.stats}
* Returns a reference to the current <code>IIOMetadata</code>
* object, or <code>null</code> is none is set.
*
* @return an <code>IIOMetadata</code> object, or <code>null</code>.
*
* @see #setMetadata
*/
public IIOMetadata getMetadata() {
return metadata;
}
/** {@collect.stats}
* Sets the <code>IIOMetadata</code> to a new object, or
* <code>null</code>.
*
* @param metadata an <code>IIOMetadata</code> object, or
* <code>null</code>.
*
* @see #getMetadata
*/
public void setMetadata(IIOMetadata metadata) {
this.metadata = metadata;
}
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.imageio.event.IIOWriteWarningListener;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.spi.ImageWriterSpi;
/** {@collect.stats}
* An abstract superclass for encoding and writing images. This class
* must be subclassed by classes that write out images in the context
* of the Java Image I/O framework.
*
* <p> <code>ImageWriter</code> objects are normally instantiated by
* the service provider class for the specific format. Service
* provider classes are registered with the <code>IIORegistry</code>,
* which uses them for format recognition and presentation of
* available format readers and writers.
*
* <p>
*
* @see ImageReader
* @see ImageWriteParam
* @see javax.imageio.spi.IIORegistry
* @see javax.imageio.spi.ImageWriterSpi
*
*/
public abstract class ImageWriter implements ImageTranscoder {
/** {@collect.stats}
* The <code>ImageWriterSpi</code> that instantiated this object,
* or <code>null</code> if its identity is not known or none
* exists. By default it is initialized to <code>null</code>.
*/
protected ImageWriterSpi originatingProvider = null;
/** {@collect.stats}
* The <code>ImageOutputStream</code> or other <code>Object</code>
* set by <code>setOutput</code> and retrieved by
* <code>getOutput</code>. By default it is initialized to
* <code>null</code>.
*/
protected Object output = null;
/** {@collect.stats}
* An array of <code>Locale</code>s that may be used to localize
* warning messages and compression setting values, or
* <code>null</code> if localization is not supported. By default
* it is initialized to <code>null</code>.
*/
protected Locale[] availableLocales = null;
/** {@collect.stats}
* The current <code>Locale</code> to be used for localization, or
* <code>null</code> if none has been set. By default it is
* initialized to <code>null</code>.
*/
protected Locale locale = null;
/** {@collect.stats}
* A <code>List</code> of currently registered
* <code>IIOWriteWarningListener</code>s, initialized by default to
* <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<IIOWriteWarningListener> warningListeners = null;
/** {@collect.stats}
* A <code>List</code> of <code>Locale</code>s, one for each
* element of <code>warningListeners</code>, initialized by default
* <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<Locale> warningLocales = null;
/** {@collect.stats}
* A <code>List</code> of currently registered
* <code>IIOWriteProgressListener</code>s, initialized by default
* <code>null</code>, which is synonymous with an empty
* <code>List</code>.
*/
protected List<IIOWriteProgressListener> progressListeners = null;
/** {@collect.stats}
* If <code>true</code>, the current write operation should be
* aborted.
*/
private boolean abortFlag = false;
/** {@collect.stats}
* Constructs an <code>ImageWriter</code> and sets its
* <code>originatingProvider</code> instance variable to the
* supplied value.
*
* <p> Subclasses that make use of extensions should provide a
* constructor with signature <code>(ImageWriterSpi,
* Object)</code> in order to retrieve the extension object. If
* the extension object is unsuitable, an
* <code>IllegalArgumentException</code> should be thrown.
*
* @param originatingProvider the <code>ImageWriterSpi</code> that
* is constructing this object, or <code>null</code>.
*/
protected ImageWriter(ImageWriterSpi originatingProvider) {
this.originatingProvider = originatingProvider;
}
/** {@collect.stats}
* Returns the <code>ImageWriterSpi</code> object that created
* this <code>ImageWriter</code>, or <code>null</code> if this
* object was not created through the <code>IIORegistry</code>.
*
* <p> The default implementation returns the value of the
* <code>originatingProvider</code> instance variable.
*
* @return an <code>ImageWriterSpi</code>, or <code>null</code>.
*
* @see ImageWriterSpi
*/
public ImageWriterSpi getOriginatingProvider() {
return originatingProvider;
}
/** {@collect.stats}
* Sets the destination to the given
* <code>ImageOutputStream</code> or other <code>Object</code>.
* The destination is assumed to be ready to accept data, and will
* not be closed at the end of each write. This allows distributed
* imaging applications to transmit a series of images over a
* single network connection. If <code>output</code> is
* <code>null</code>, any currently set output will be removed.
*
* <p> If <code>output</code> is an
* <code>ImageOutputStream</code>, calls to the
* <code>write</code>, <code>writeToSequence</code>, and
* <code>prepareWriteEmpty</code>/<code>endWriteEmpty</code>
* methods will preserve the existing contents of the stream.
* Other write methods, such as <code>writeInsert</code>,
* <code>replaceStreamMetadata</code>,
* <code>replaceImageMetadata</code>, <code>replacePixels</code>,
* <code>prepareInsertEmpty</code>/<code>endInsertEmpty</code>,
* and <code>endWriteSequence</code>, require the full contents
* of the stream to be readable and writable, and may alter any
* portion of the stream.
*
* <p> Use of a general <code>Object</code> other than an
* <code>ImageOutputStream</code> is intended for writers that
* interact directly with an output device or imaging protocol.
* The set of legal classes is advertised by the writer's service
* provider's <code>getOutputTypes</code> method; most writers
* will return a single-element array containing only
* <code>ImageOutputStream.class</code> to indicate that they
* accept only an <code>ImageOutputStream</code>.
*
* <p> The default implementation sets the <code>output</code>
* instance variable to the value of <code>output</code> after
* checking <code>output</code> against the set of classes
* advertised by the originating provider, if there is one.
*
* @param output the <code>ImageOutputStream</code> or other
* <code>Object</code> to use for future writing.
*
* @exception IllegalArgumentException if <code>output</code> is
* not an instance of one of the classes returned by the
* originating service provider's <code>getOutputTypes</code>
* method.
*
* @see #getOutput
*/
public void setOutput(Object output) {
if (output != null) {
ImageWriterSpi provider = getOriginatingProvider();
if (provider != null) {
Class[] classes = provider.getOutputTypes();
boolean found = false;
for (int i = 0; i < classes.length; i++) {
if (classes[i].isInstance(output)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Illegal output type!");
}
}
}
this.output = output;
}
/** {@collect.stats}
* Returns the <code>ImageOutputStream</code> or other
* <code>Object</code> set by the most recent call to the
* <code>setOutput</code> method. If no destination has been
* set, <code>null</code> is returned.
*
* <p> The default implementation returns the value of the
* <code>output</code> instance variable.
*
* @return the <code>Object</code> that was specified using
* <code>setOutput</code>, or <code>null</code>.
*
* @see #setOutput
*/
public Object getOutput() {
return output;
}
// Localization
/** {@collect.stats}
* Returns an array of <code>Locale</code>s that may be used to
* localize warning listeners and compression settings. A return
* value of <code>null</code> indicates that localization is not
* supported.
*
* <p> The default implementation returns a clone of the
* <code>availableLocales</code> instance variable if it is
* non-<code>null</code>, or else returns <code>null</code>.
*
* @return an array of <code>Locale</code>s that may be used as
* arguments to <code>setLocale</code>, or <code>null</code>.
*/
public Locale[] getAvailableLocales() {
return (availableLocales == null) ?
null : (Locale[])availableLocales.clone();
}
/** {@collect.stats}
* Sets the current <code>Locale</code> of this
* <code>ImageWriter</code> to the given value. A value of
* <code>null</code> removes any previous setting, and indicates
* that the writer should localize as it sees fit.
*
* <p> The default implementation checks <code>locale</code>
* against the values returned by
* <code>getAvailableLocales</code>, and sets the
* <code>locale</code> instance variable if it is found. If
* <code>locale</code> is <code>null</code>, the instance variable
* is set to <code>null</code> without any checking.
*
* @param locale the desired <code>Locale</code>, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>locale</code> is
* non-<code>null</code> but is not one of the values returned by
* <code>getAvailableLocales</code>.
*
* @see #getLocale
*/
public void setLocale(Locale locale) {
if (locale != null) {
Locale[] locales = getAvailableLocales();
boolean found = false;
if (locales != null) {
for (int i = 0; i < locales.length; i++) {
if (locale.equals(locales[i])) {
found = true;
break;
}
}
}
if (!found) {
throw new IllegalArgumentException("Invalid locale!");
}
}
this.locale = locale;
}
/** {@collect.stats}
* Returns the currently set <code>Locale</code>, or
* <code>null</code> if none has been set.
*
* <p> The default implementation returns the value of the
* <code>locale</code> instance variable.
*
* @return the current <code>Locale</code>, or <code>null</code>.
*
* @see #setLocale
*/
public Locale getLocale() {
return locale;
}
// Write params
/** {@collect.stats}
* Returns a new <code>ImageWriteParam</code> object of the
* appropriate type for this file format containing default
* values, that is, those values that would be used
* if no <code>ImageWriteParam</code> object were specified. This
* is useful as a starting point for tweaking just a few parameters
* and otherwise leaving the default settings alone.
*
* <p> The default implementation constructs and returns a new
* <code>ImageWriteParam</code> object that does not allow tiling,
* progressive encoding, or compression, and that will be
* localized for the current <code>Locale</code> (<i>i.e.</i>,
* what you would get by calling <code>new
* ImageWriteParam(getLocale())</code>.
*
* <p> Individual plug-ins may return an instance of
* <code>ImageWriteParam</code> with additional optional features
* enabled, or they may return an instance of a plug-in specific
* subclass of <code>ImageWriteParam</code>.
*
* @return a new <code>ImageWriteParam</code> object containing
* default values.
*/
public ImageWriteParam getDefaultWriteParam() {
return new ImageWriteParam(getLocale());
}
// Metadata
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object containing default
* values for encoding a stream of images. The contents of the
* object may be manipulated using either the XML tree structure
* returned by the <code>IIOMetadata.getAsTree</code> method, an
* <code>IIOMetadataController</code> object, or via plug-in
* specific interfaces, and the resulting data supplied to one of
* the <code>write</code> methods that take a stream metadata
* parameter.
*
* <p> An optional <code>ImageWriteParam</code> may be supplied
* for cases where it may affect the structure of the stream
* metadata.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> Writers that do not make use of stream metadata
* (<i>e.g.</i>, writers for single-image formats) should return
* <code>null</code>.
*
* @param param an <code>ImageWriteParam</code> that will be used to
* encode the image, or <code>null</code>.
*
* @return an <code>IIOMetadata</code> object.
*/
public abstract IIOMetadata
getDefaultStreamMetadata(ImageWriteParam param);
/** {@collect.stats}
* Returns an <code>IIOMetadata</code> object containing default
* values for encoding an image of the given type. The contents
* of the object may be manipulated using either the XML tree
* structure returned by the <code>IIOMetadata.getAsTree</code>
* method, an <code>IIOMetadataController</code> object, or via
* plug-in specific interfaces, and the resulting data supplied to
* one of the <code>write</code> methods that take a stream
* metadata parameter.
*
* <p> An optional <code>ImageWriteParam</code> may be supplied
* for cases where it may affect the structure of the image
* metadata.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* @param imageType an <code>ImageTypeSpecifier</code> indicating the
* format of the image to be written later.
* @param param an <code>ImageWriteParam</code> that will be used to
* encode the image, or <code>null</code>.
*
* @return an <code>IIOMetadata</code> object.
*/
public abstract IIOMetadata
getDefaultImageMetadata(ImageTypeSpecifier imageType,
ImageWriteParam param);
// comment inherited
public abstract IIOMetadata convertStreamMetadata(IIOMetadata inData,
ImageWriteParam param);
// comment inherited
public abstract IIOMetadata
convertImageMetadata(IIOMetadata inData,
ImageTypeSpecifier imageType,
ImageWriteParam param);
// Thumbnails
/** {@collect.stats}
* Returns the number of thumbnails suported by the format being
* written, given the image type and any additional write
* parameters and metadata objects that will be used during
* encoding. A return value of <code>-1</code> indicates that
* insufficient information is available.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* for cases where it may affect thumbnail handling.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation returns 0.
*
* @param imageType an <code>ImageTypeSpecifier</code> indicating
* the type of image to be written, or <code>null</code>.
* @param param the <code>ImageWriteParam</code> that will be used for
* writing, or <code>null</code>.
* @param streamMetadata an <code>IIOMetadata</code> object that will
* be used for writing, or <code>null</code>.
* @param imageMetadata an <code>IIOMetadata</code> object that will
* be used for writing, or <code>null</code>.
*
* @return the number of thumbnails that may be written given the
* supplied parameters, or <code>-1</code> if insufficient
* information is available.
*/
public int getNumThumbnailsSupported(ImageTypeSpecifier imageType,
ImageWriteParam param,
IIOMetadata streamMetadata,
IIOMetadata imageMetadata) {
return 0;
}
/** {@collect.stats}
* Returns an array of <code>Dimension</code>s indicating the
* legal size ranges for thumbnail images as they will be encoded
* in the output file or stream. This information is merely
* advisory; the writer will resize any supplied thumbnails as
* necessary.
*
* <p> The information is returned as a set of pairs; the first
* element of a pair contains an (inclusive) minimum width and
* height, and the second element contains an (inclusive) maximum
* width and height. Together, each pair defines a valid range of
* sizes. To specify a fixed size, the same width and height will
* appear for both elements. A return value of <code>null</code>
* indicates that the size is arbitrary or unknown.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* for cases where it may affect thumbnail handling.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation returns <code>null</code>.
*
* @param imageType an <code>ImageTypeSpecifier</code> indicating the
* type of image to be written, or <code>null</code>.
* @param param the <code>ImageWriteParam</code> that will be used for
* writing, or <code>null</code>.
* @param streamMetadata an <code>IIOMetadata</code> object that will
* be used for writing, or <code>null</code>.
* @param imageMetadata an <code>IIOMetadata</code> object that will
* be used for writing, or <code>null</code>.
*
* @return an array of <code>Dimension</code>s with an even length
* of at least two, or <code>null</code>.
*/
public Dimension[] getPreferredThumbnailSizes(ImageTypeSpecifier imageType,
ImageWriteParam param,
IIOMetadata streamMetadata,
IIOMetadata imageMetadata) {
return null;
}
/** {@collect.stats}
* Returns <code>true</code> if the methods that take an
* <code>IIOImage</code> parameter are capable of dealing with a
* <code>Raster</code> (as opposed to <code>RenderedImage</code>)
* source image. If this method returns <code>false</code>, then
* those methods will throw an
* <code>UnsupportedOperationException</code> if supplied with an
* <code>IIOImage</code> containing a <code>Raster</code>.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if <code>Raster</code> sources are
* supported.
*/
public boolean canWriteRasters() {
return false;
}
/** {@collect.stats}
* Appends a complete image stream containing a single image and
* associated stream and image metadata and thumbnails to the
* output. Any necessary header information is included. If the
* output is an <code>ImageOutputStream</code>, its existing
* contents prior to the current seek position are not affected,
* and need not be readable or writable.
*
* <p> The output must have been set beforehand using the
* <code>setOutput</code> method.
*
* <p> Stream metadata may optionally be supplied; if it is
* <code>null</code>, default stream metadata will be used.
*
* <p> If <code>canWriteRasters</code> returns <code>true</code>,
* the <code>IIOImage</code> may contain a <code>Raster</code>
* source. Otherwise, it must contain a
* <code>RenderedImage</code> source.
*
* <p> The supplied thumbnails will be resized if needed, and any
* thumbnails in excess of the supported number will be ignored.
* If the format requires additional thumbnails that are not
* provided, the writer should generate them internally.
*
* <p> An <code>ImageWriteParam</code> may
* optionally be supplied to control the writing process. If
* <code>param</code> is <code>null</code>, a default write param
* will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* @param streamMetadata an <code>IIOMetadata</code> object representing
* stream metadata, or <code>null</code> to use default values.
* @param image an <code>IIOImage</code> object containing an
* image, thumbnails, and metadata to be written.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if <code>image</code>
* contains a <code>Raster</code> and <code>canWriteRasters</code>
* returns <code>false</code>.
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public abstract void write(IIOMetadata streamMetadata,
IIOImage image,
ImageWriteParam param) throws IOException;
/** {@collect.stats}
* Appends a complete image stream containing a single image with
* default metadata and thumbnails to the output. This method is
* a shorthand for <code>write(null, image, null)</code>.
*
* @param image an <code>IIOImage</code> object containing an
* image, thumbnails, and metadata to be written.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
* @exception UnsupportedOperationException if <code>image</code>
* contains a <code>Raster</code> and <code>canWriteRasters</code>
* returns <code>false</code>.
* @exception IOException if an error occurs during writing.
*/
public void write(IIOImage image) throws IOException {
write(null, image, null);
}
/** {@collect.stats}
* Appends a complete image stream consisting of a single image
* with default metadata and thumbnails to the output. This
* method is a shorthand for <code>write(null, new IIOImage(image,
* null, null), null)</code>.
*
* @param image a <code>RenderedImage</code> to be written.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public void write(RenderedImage image) throws IOException {
write(null, new IIOImage(image, null, null), null);
}
// Check that the output has been set, then throw an
// UnsupportedOperationException.
private void unsupported() {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
throw new UnsupportedOperationException("Unsupported write variant!");
}
// Sequence writes
/** {@collect.stats}
* Returns <code>true</code> if the writer is able to append an
* image to an image stream that already contains header
* information and possibly prior images.
*
* <p> If <code>canWriteSequence</code> returns <code>false</code>,
* <code>writeToSequence</code> and <code>endWriteSequence</code>
* will throw an <code>UnsupportedOperationException</code>.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if images may be appended sequentially.
*/
public boolean canWriteSequence() {
return false;
}
/** {@collect.stats}
* Prepares a stream to accept a series of subsequent
* <code>writeToSequence</code> calls, using the provided stream
* metadata object. The metadata will be written to the stream if
* it should precede the image data. If the argument is <code>null</code>,
* default stream metadata is used.
*
* <p> If the output is an <code>ImageOutputStream</code>, the existing
* contents of the output prior to the current seek position are
* flushed, and need not be readable or writable. If the format
* requires that <code>endWriteSequence</code> be able to rewind to
* patch up the header information, such as for a sequence of images
* in a single TIFF file, then the metadata written by this method
* must remain in a writable portion of the stream. Other formats
* may flush the stream after this method and after each image.
*
* <p> If <code>canWriteSequence</code> returns <code>false</code>,
* this method will throw an
* <code>UnsupportedOperationException</code>.
*
* <p> The output must have been set beforehand using either
* the <code>setOutput</code> method.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param streamMetadata A stream metadata object, or <code>null</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canWriteSequence</code> returns <code>false</code>.
* @exception IOException if an error occurs writing the stream
* metadata.
*/
public void prepareWriteSequence(IIOMetadata streamMetadata)
throws IOException {
unsupported();
}
/** {@collect.stats}
* Appends a single image and possibly associated metadata and
* thumbnails, to the output. If the output is an
* <code>ImageOutputStream</code>, the existing contents of the
* output prior to the current seek position may be flushed, and
* need not be readable or writable, unless the plug-in needs to
* be able to patch up the header information when
* <code>endWriteSequence</code> is called (<italic>e.g.</italic> TIFF).
*
* <p> If <code>canWriteSequence</code> returns <code>false</code>,
* this method will throw an
* <code>UnsupportedOperationException</code>.
*
* <p> The output must have been set beforehand using
* the <code>setOutput</code> method.
*
* <p> <code>prepareWriteSequence</code> must have been called
* beforehand, or an <code>IllegalStateException</code> is thrown.
*
* <p> If <code>canWriteRasters</code> returns <code>true</code>,
* the <code>IIOImage</code> may contain a <code>Raster</code>
* source. Otherwise, it must contain a
* <code>RenderedImage</code> source.
*
* <p> The supplied thumbnails will be resized if needed, and any
* thumbnails in excess of the supported number will be ignored.
* If the format requires additional thumbnails that are not
* provided, the writer will generate them internally.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param image an <code>IIOImage</code> object containing an
* image, thumbnails, and metadata to be written.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set, or <code>prepareWriteSequence</code> has not been called.
* @exception UnsupportedOperationException if
* <code>canWriteSequence</code> returns <code>false</code>.
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
* @exception UnsupportedOperationException if <code>image</code>
* contains a <code>Raster</code> and <code>canWriteRasters</code>
* returns <code>false</code>.
* @exception IOException if an error occurs during writing.
*/
public void writeToSequence(IIOImage image, ImageWriteParam param)
throws IOException {
unsupported();
}
/** {@collect.stats}
* Completes the writing of a sequence of images begun with
* <code>prepareWriteSequence</code>. Any stream metadata that
* should come at the end of the sequence of images is written out,
* and any header information at the beginning of the sequence is
* patched up if necessary. If the output is an
* <code>ImageOutputStream</code>, data through the stream metadata
* at the end of the sequence are flushed and need not be readable
* or writable.
*
* <p> If <code>canWriteSequence</code> returns <code>false</code>,
* this method will throw an
* <code>UnsupportedOperationException</code>.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @exception IllegalStateException if the output has not
* been set, or <code>prepareWriteSequence</code> has not been called.
* @exception UnsupportedOperationException if
* <code>canWriteSequence</code> returns <code>false</code>.
* @exception IOException if an error occurs during writing.
*/
public void endWriteSequence() throws IOException {
unsupported();
}
// Metadata replacement
/** {@collect.stats}
* Returns <code>true</code> if it is possible to replace the
* stream metadata already present in the output.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>.
*
* @return <code>true</code> if replacement of stream metadata is
* allowed.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IOException if an I/O error occurs during the query.
*/
public boolean canReplaceStreamMetadata() throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Replaces the stream metadata in the output with new
* information. If the output is an
* <code>ImageOutputStream</code>, the prior contents of the
* stream are examined and possibly edited to make room for the
* new data. All of the prior contents of the output must be
* available for reading and writing.
*
* <p> If <code>canReplaceStreamMetadata</code> returns
* <code>false</code>, an
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param streamMetadata an <code>IIOMetadata</code> object representing
* stream metadata, or <code>null</code> to use default values.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if the
* <code>canReplaceStreamMetadata</code> returns
* <code>false</code>. modes do not include
* @exception IOException if an error occurs during writing.
*/
public void replaceStreamMetadata(IIOMetadata streamMetadata)
throws IOException {
unsupported();
}
/** {@collect.stats}
* Returns <code>true</code> if it is possible to replace the
* image metadata associated with an existing image with index
* <code>imageIndex</code>. If this method returns
* <code>false</code>, a call to
* <code>replaceImageMetadata(imageIndex)</code> will throw an
* <code>UnsupportedOperationException</code>.
*
* <p> A writer that does not support any image metadata
* replacement may return <code>false</code> without performing
* bounds checking on the index.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>
* without checking the value of <code>imageIndex</code>.
*
* @param imageIndex the index of the image whose metadata is to
* be replaced.
*
* @return <code>true</code> if the image metadata of the given
* image can be replaced.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IndexOutOfBoundsException if the writer supports
* image metadata replacement in general, but
* <code>imageIndex</code> is less than 0 or greater than the
* largest available index.
* @exception IOException if an I/O error occurs during the query.
*/
public boolean canReplaceImageMetadata(int imageIndex)
throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Replaces the image metadata associated with an existing image.
*
* <p> If <code>canReplaceImageMetadata(imageIndex)</code> returns
* <code>false</code>, an
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index of the image whose metadata is to
* be replaced.
* @param imageMetadata an <code>IIOMetadata</code> object
* representing image metadata, or <code>null</code>.
*
* @exception IllegalStateException if the output has not been
* set.
* @exception UnsupportedOperationException if
* <code>canReplaceImageMetadata</code> returns
* <code>false</code>.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is less than 0 or greater than the largest available index.
* @exception IOException if an error occurs during writing.
*/
public void replaceImageMetadata(int imageIndex,
IIOMetadata imageMetadata)
throws IOException {
unsupported();
}
// Image insertion
/** {@collect.stats}
* Returns <code>true</code> if the writer supports the insertion
* of a new image at the given index. Existing images with
* indices greater than or equal to the insertion index will have
* their indices increased by 1. A value for
* <code>imageIndex</code> of <code>-1</code> may be used to
* signify an index one larger than the current largest index.
*
* <p> A writer that does not support any image insertion may
* return <code>false</code> without performing bounds checking on
* the index.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>
* withour checking the value of <code>imageIndex</code>.
*
* @param imageIndex the index at which the image is to be
* inserted.
*
* @return <code>true</code> if an image may be inserted at the
* given index.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IndexOutOfBoundsException if the writer supports
* image insertion in general, but <code>imageIndex</code> is less
* than -1 or greater than the largest available index.
* @exception IOException if an I/O error occurs during the query.
*/
public boolean canInsertImage(int imageIndex) throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Inserts a new image into an existing image stream. Existing
* images with an index greater than <code>imageIndex</code> are
* preserved, and their indices are each increased by 1. A value
* for <code>imageIndex</code> of -1 may be used to signify an
* index one larger than the previous largest index; that is, it
* will cause the image to be logically appended to the end of the
* sequence. If the output is an <code>ImageOutputStream</code>,
* the entirety of the stream must be both readable and writeable.
*
* <p> If <code>canInsertImage(imageIndex)</code> returns
* <code>false</code>, an
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index at which to write the image.
* @param image an <code>IIOImage</code> object containing an
* image, thumbnails, and metadata to be written.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canInsertImage(imageIndex)</code> returns <code>false</code>.
* @exception IllegalArgumentException if <code>image</code> is
* <code>null</code>.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is less than -1 or greater than the largest available index.
* @exception UnsupportedOperationException if <code>image</code>
* contains a <code>Raster</code> and <code>canWriteRasters</code>
* returns <code>false</code>.
* @exception IOException if an error occurs during writing.
*/
public void writeInsert(int imageIndex,
IIOImage image,
ImageWriteParam param) throws IOException {
unsupported();
}
// Image removal
/** {@collect.stats}
* Returns <code>true</code> if the writer supports the removal
* of an existing image at the given index. Existing images with
* indices greater than the insertion index will have
* their indices decreased by 1.
*
* <p> A writer that does not support any image removal may
* return <code>false</code> without performing bounds checking on
* the index.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>
* without checking the value of <code>imageIndex</code>.
*
* @param imageIndex the index of the image to be removed.
*
* @return <code>true</code> if it is possible to remove the given
* image.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception IndexOutOfBoundsException if the writer supports
* image removal in general, but <code>imageIndex</code> is less
* than 0 or greater than the largest available index.
* @exception IOException if an I/O error occurs during the
* query.
*/
public boolean canRemoveImage(int imageIndex) throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Removes an image from the stream.
*
* <p> If <code>canRemoveImage(imageIndex)</code> returns false,
* an <code>UnsupportedOperationException</code>will be thrown.
*
* <p> The removal may or may not cause a reduction in the actual
* file size.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index of the image to be removed.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canRemoveImage(imageIndex)</code> returns <code>false</code>.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is less than 0 or greater than the largest available index.
* @exception IOException if an I/O error occurs during the
* removal.
*/
public void removeImage(int imageIndex) throws IOException {
unsupported();
}
// Empty images
/** {@collect.stats}
* Returns <code>true</code> if the writer supports the writing of
* a complete image stream consisting of a single image with
* undefined pixel values and associated metadata and thumbnails
* to the output. The pixel values may be defined by future
* calls to the <code>replacePixels</code> methods. If the output
* is an <code>ImageOutputStream</code>, its existing contents
* prior to the current seek position are not affected, and need
* not be readable or writable.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>.
*
* @return <code>true</code> if the writing of complete image
* stream with contents to be defined later is supported.
*
* @exception IllegalStateException if the output has not been
* set.
* @exception IOException if an I/O error occurs during the
* query.
*/
public boolean canWriteEmpty() throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Begins the writing of a complete image stream, consisting of a
* single image with undefined pixel values and associated
* metadata and thumbnails, to the output. The pixel values will
* be defined by future calls to the <code>replacePixels</code>
* methods. If the output is an <code>ImageOutputStream</code>,
* its existing contents prior to the current seek position are
* not affected, and need not be readable or writable.
*
* <p> The writing is not complete until a call to
* <code>endWriteEmpty</code> occurs. Calls to
* <code>prepareReplacePixels</code>, <code>replacePixels</code>,
* and <code>endReplacePixels</code> may occur between calls to
* <code>prepareWriteEmpty</code> and <code>endWriteEmpty</code>.
* However, calls to <code>prepareWriteEmpty</code> cannot be
* nested, and calls to <code>prepareWriteEmpty</code> and
* <code>prepareInsertEmpty</code> may not be interspersed.
*
* <p> If <code>canWriteEmpty</code> returns <code>false</code>,
* an <code>UnsupportedOperationException</code> will be thrown.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param streamMetadata an <code>IIOMetadata</code> object representing
* stream metadata, or <code>null</code> to use default values.
* @param imageType an <code>ImageTypeSpecifier</code> describing
* the layout of the image.
* @param width the width of the image.
* @param height the height of the image.
* @param imageMetadata an <code>IIOMetadata</code> object
* representing image metadata, or <code>null</code>.
* @param thumbnails a <code>List</code> of
* <code>BufferedImage</code> thumbnails for this image, or
* <code>null</code>.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canWriteEmpty</code> returns <code>false</code>.
* @exception IllegalStateException if a previous call to
* <code>prepareWriteEmpty</code> has been made without a
* corresponding call to <code>endWriteEmpty</code>.
* @exception IllegalStateException if a previous call to
* <code>prepareInsertEmpty</code> has been made without a
* corresponding call to <code>endInsertEmpty</code>.
* @exception IllegalArgumentException if <code>imageType</code>
* is <code>null</code> or <code>thumbnails</code> contains
* <code>null</code> references or objects other than
* <code>BufferedImage</code>s.
* @exception IllegalArgumentException if width or height are less
* than 1.
* @exception IOException if an I/O error occurs during writing.
*/
public void prepareWriteEmpty(IIOMetadata streamMetadata,
ImageTypeSpecifier imageType,
int width, int height,
IIOMetadata imageMetadata,
List<? extends BufferedImage> thumbnails,
ImageWriteParam param) throws IOException {
unsupported();
}
/** {@collect.stats}
* Completes the writing of a new image that was begun with a
* prior call to <code>prepareWriteEmpty</code>.
*
* <p> If <code>canWriteEmpty()</code> returns <code>false</code>,
* an <code>UnsupportedOperationException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canWriteEmpty(imageIndex)</code> returns
* <code>false</code>.
* @exception IllegalStateException if a previous call to
* <code>prepareWriteEmpty</code> without a corresponding call to
* <code>endWriteEmpty</code> has not been made.
* @exception IllegalStateException if a previous call to
* <code>prepareInsertEmpty</code> without a corresponding call to
* <code>endInsertEmpty</code> has been made.
* @exception IllegalStateException if a call to
* <code>prepareReiplacePixels</code> has been made without a
* matching call to <code>endReplacePixels</code>.
* @exception IOException if an I/O error occurs during writing.
*/
public void endWriteEmpty() throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
throw new IllegalStateException("No call to prepareWriteEmpty!");
}
/** {@collect.stats}
* Returns <code>true</code> if the writer supports the insertion
* of a new, empty image at the given index. The pixel values of
* the image are undefined, and may be specified in pieces using
* the <code>replacePixels</code> methods. Existing images with
* indices greater than or equal to the insertion index will have
* their indices increased by 1. A value for
* <code>imageIndex</code> of <code>-1</code> may be used to
* signify an index one larger than the current largest index.
*
* <p> A writer that does not support insertion of empty images
* may return <code>false</code> without performing bounds
* checking on the index.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>
* without checking the value of <code>imageIndex</code>.
*
* @param imageIndex the index at which the image is to be
* inserted.
*
* @return <code>true</code> if an empty image may be inserted at
* the given index.
*
* @exception IllegalStateException if the output has not been
* set.
* @exception IndexOutOfBoundsException if the writer supports
* empty image insertion in general, but <code>imageIndex</code>
* is less than -1 or greater than the largest available index.
* @exception IOException if an I/O error occurs during the
* query.
*/
public boolean canInsertEmpty(int imageIndex) throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Begins the insertion of a new image with undefined pixel values
* into an existing image stream. Existing images with an index
* greater than <code>imageIndex</code> are preserved, and their
* indices are each increased by 1. A value for
* <code>imageIndex</code> of -1 may be used to signify an index
* one larger than the previous largest index; that is, it will
* cause the image to be logically appended to the end of the
* sequence. If the output is an <code>ImageOutputStream</code>,
* the entirety of the stream must be both readable and writeable.
*
* <p> The image contents may be
* supplied later using the <code>replacePixels</code> method.
* The insertion is not complete until a call to
* <code>endInsertEmpty</code> occurs. Calls to
* <code>prepareReplacePixels</code>, <code>replacePixels</code>,
* and <code>endReplacePixels</code> may occur between calls to
* <code>prepareInsertEmpty</code> and
* <code>endInsertEmpty</code>. However, calls to
* <code>prepareInsertEmpty</code> cannot be nested, and calls to
* <code>prepareWriteEmpty</code> and
* <code>prepareInsertEmpty</code> may not be interspersed.
*
* <p> If <code>canInsertEmpty(imageIndex)</code> returns
* <code>false</code>, an
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index at which to write the image.
* @param imageType an <code>ImageTypeSpecifier</code> describing
* the layout of the image.
* @param width the width of the image.
* @param height the height of the image.
* @param imageMetadata an <code>IIOMetadata</code> object
* representing image metadata, or <code>null</code>.
* @param thumbnails a <code>List</code> of
* <code>BufferedImage</code> thumbnails for this image, or
* <code>null</code>.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canInsertEmpty(imageIndex)</code> returns
* <code>false</code>.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is less than -1 or greater than the largest available index.
* @exception IllegalStateException if a previous call to
* <code>prepareInsertEmpty</code> has been made without a
* corresponding call to <code>endInsertEmpty</code>.
* @exception IllegalStateException if a previous call to
* <code>prepareWriteEmpty</code> has been made without a
* corresponding call to <code>endWriteEmpty</code>.
* @exception IllegalArgumentException if <code>imageType</code>
* is <code>null</code> or <code>thumbnails</code> contains
* <code>null</code> references or objects other than
* <code>BufferedImage</code>s.
* @exception IllegalArgumentException if width or height are less
* than 1.
* @exception IOException if an I/O error occurs during writing.
*/
public void prepareInsertEmpty(int imageIndex,
ImageTypeSpecifier imageType,
int width, int height,
IIOMetadata imageMetadata,
List<? extends BufferedImage> thumbnails,
ImageWriteParam param) throws IOException {
unsupported();
}
/** {@collect.stats}
* Completes the insertion of a new image that was begun with a
* prior call to <code>prepareInsertEmpty</code>.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canInsertEmpty(imageIndex)</code> returns
* <code>false</code>.
* @exception IllegalStateException if a previous call to
* <code>prepareInsertEmpty</code> without a corresponding call to
* <code>endInsertEmpty</code> has not been made.
* @exception IllegalStateException if a previous call to
* <code>prepareWriteEmpty</code> without a corresponding call to
* <code>endWriteEmpty</code> has been made.
* @exception IllegalStateException if a call to
* <code>prepareReplacePixels</code> has been made without a
* matching call to <code>endReplacePixels</code>.
* @exception IOException if an I/O error occurs during writing.
*/
public void endInsertEmpty() throws IOException {
unsupported();
}
// Pixel replacement
/** {@collect.stats}
* Returns <code>true</code> if the writer allows pixels of the
* given image to be replaced using the <code>replacePixels</code>
* methods.
*
* <p> A writer that does not support any pixel replacement may
* return <code>false</code> without performing bounds checking on
* the index.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise returns <code>false</code>
* without checking the value of <code>imageIndex</code>.
*
* @param imageIndex the index of the image whose pixels are to be
* replaced.
*
* @return <code>true</code> if the pixels of the given
* image can be replaced.
*
* @exception IllegalStateException if the output has not been
* set.
* @exception IndexOutOfBoundsException if the writer supports
* pixel replacement in general, but <code>imageIndex</code> is
* less than 0 or greater than the largest available index.
* @exception IOException if an I/O error occurs during the query.
*/
public boolean canReplacePixels(int imageIndex) throws IOException {
if (getOutput() == null) {
throw new IllegalStateException("getOutput() == null!");
}
return false;
}
/** {@collect.stats}
* Prepares the writer to handle a series of calls to the
* <code>replacePixels</code> methods. The affected pixel area
* will be clipped against the supplied
*
* <p> If <code>canReplacePixels</code> returns
* <code>false</code>, and
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param imageIndex the index of the image whose pixels are to be
* replaced.
* @param region a <code>Rectangle</code> that will be used to clip
* future pixel regions.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canReplacePixels(imageIndex)</code> returns
* <code>false</code>.
* @exception IndexOutOfBoundsException if <code>imageIndex</code>
* is less than 0 or greater than the largest available index.
* @exception IllegalStateException if there is a previous call to
* <code>prepareReplacePixels</code> without a matching call to
* <code>endReplacePixels</code> (<i>i.e.</i>, nesting is not
* allowed).
* @exception IllegalArgumentException if <code>region</code> is
* <code>null</code> or has a width or height less than 1.
* @exception IOException if an I/O error occurs during the
* preparation.
*/
public void prepareReplacePixels(int imageIndex,
Rectangle region) throws IOException {
unsupported();
}
/** {@collect.stats}
* Replaces a portion of an image already present in the output
* with a portion of the given image. The image data must match,
* or be convertible to, the image layout of the existing image.
*
* <p> The destination region is specified in the
* <code>param</code> argument, and will be clipped to the image
* boundaries and the region supplied to
* <code>prepareReplacePixels</code>. At least one pixel of the
* source must not be clipped, or an exception is thrown.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> This method may only be called after a call to
* <code>prepareReplacePixels</code>, or else an
* <code>IllegalStateException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param image a <code>RenderedImage</code> containing source
* pixels.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canReplacePixels(imageIndex)</code> returns
* <code>false</code>.
* @exception IllegalStateException if there is no previous call to
* <code>prepareReplacePixels</code> without a matching call to
* <code>endReplacePixels</code>.
* @exception IllegalArgumentException if any of the following are true:
* <ul>
* <li> <code>image</code> is <code>null</code>.
* <li> <code>param</code> is <code>null</code>.
* <li> the intersected region does not contain at least one pixel.
* <li> the layout of <code>image</code> does not match, or this
* writer cannot convert it to, the existing image layout.
* </ul>
* @exception IOException if an I/O error occurs during writing.
*/
public void replacePixels(RenderedImage image, ImageWriteParam param)
throws IOException {
unsupported();
}
/** {@collect.stats}
* Replaces a portion of an image already present in the output
* with a portion of the given <code>Raster</code>. The image
* data must match, or be convertible to, the image layout of the
* existing image.
*
* <p> An <code>ImageWriteParam</code> may optionally be supplied
* to control the writing process. If <code>param</code> is
* <code>null</code>, a default write param will be used.
*
* <p> The destination region is specified in the
* <code>param</code> argument, and will be clipped to the image
* boundaries and the region supplied to
* <code>prepareReplacePixels</code>. At least one pixel of the
* source must not be clipped, or an exception is thrown.
*
* <p> If the supplied <code>ImageWriteParam</code> contains
* optional setting values not supported by this writer (<i>e.g.</i>
* progressive encoding or any format-specific settings), they
* will be ignored.
*
* <p> This method may only be called after a call to
* <code>prepareReplacePixels</code>, or else an
* <code>IllegalStateException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @param raster a <code>Raster</code> containing source
* pixels.
* @param param an <code>ImageWriteParam</code>, or
* <code>null</code> to use a default
* <code>ImageWriteParam</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canReplacePixels(imageIndex)</code> returns
* <code>false</code>.
* @exception IllegalStateException if there is no previous call to
* <code>prepareReplacePixels</code> without a matching call to
* <code>endReplacePixels</code>.
* @exception UnsupportedOperationException if
* <code>canWriteRasters</code> returns <code>false</code>.
* @exception IllegalArgumentException if any of the following are true:
* <ul>
* <li> <code>raster</code> is <code>null</code>.
* <li> <code>param</code> is <code>null</code>.
* <li> the intersected region does not contain at least one pixel.
* <li> the layout of <code>raster</code> does not match, or this
* writer cannot convert it to, the existing image layout.
* </ul>
* @exception IOException if an I/O error occurs during writing.
*/
public void replacePixels(Raster raster, ImageWriteParam param)
throws IOException {
unsupported();
}
/** {@collect.stats}
* Terminates a sequence of calls to <code>replacePixels</code>.
*
* <p> If <code>canReplacePixels</code> returns
* <code>false</code>, and
* <code>UnsupportedOperationException</code> will be thrown.
*
* <p> The default implementation throws an
* <code>IllegalStateException</code> if the output is
* <code>null</code>, and otherwise throws an
* <code>UnsupportedOperationException</code>.
*
* @exception IllegalStateException if the output has not
* been set.
* @exception UnsupportedOperationException if
* <code>canReplacePixels(imageIndex)</code> returns
* <code>false</code>.
* @exception IllegalStateException if there is no previous call
* to <code>prepareReplacePixels</code> without a matching call to
* <code>endReplacePixels</code>.
* @exception IOException if an I/O error occurs during writing.
*/
public void endReplacePixels() throws IOException {
unsupported();
}
// Abort
/** {@collect.stats}
* Requests that any current write operation be aborted. The
* contents of the output following the abort will be undefined.
*
* <p> Writers should call <code>clearAbortRequest</code> at the
* beginning of each write operation, and poll the value of
* <code>abortRequested</code> regularly during the write.
*/
public synchronized void abort() {
this.abortFlag = true;
}
/** {@collect.stats}
* Returns <code>true</code> if a request to abort the current
* write operation has been made since the writer was instantiated or
* <code>clearAbortRequest</code> was called.
*
* @return <code>true</code> if the current write operation should
* be aborted.
*
* @see #abort
* @see #clearAbortRequest
*/
protected synchronized boolean abortRequested() {
return this.abortFlag;
}
/** {@collect.stats}
* Clears any previous abort request. After this method has been
* called, <code>abortRequested</code> will return
* <code>false</code>.
*
* @see #abort
* @see #abortRequested
*/
protected synchronized void clearAbortRequest() {
this.abortFlag = false;
}
// Listeners
/** {@collect.stats}
* Adds an <code>IIOWriteWarningListener</code> to the list of
* registered warning listeners. If <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken. Messages sent to the given listener will be
* localized, if possible, to match the current
* <code>Locale</code>. If no <code>Locale</code> has been set,
* warning messages may be localized as the writer sees fit.
*
* @param listener an <code>IIOWriteWarningListener</code> to be
* registered.
*
* @see #removeIIOWriteWarningListener
*/
public void addIIOWriteWarningListener(IIOWriteWarningListener listener) {
if (listener == null) {
return;
}
warningListeners = ImageReader.addToList(warningListeners, listener);
warningLocales = ImageReader.addToList(warningLocales, getLocale());
}
/** {@collect.stats}
* Removes an <code>IIOWriteWarningListener</code> from the list
* of registered warning listeners. If the listener was not
* previously registered, or if <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an <code>IIOWriteWarningListener</code> to be
* deregistered.
*
* @see #addIIOWriteWarningListener
*/
public
void removeIIOWriteWarningListener(IIOWriteWarningListener listener) {
if (listener == null || warningListeners == null) {
return;
}
int index = warningListeners.indexOf(listener);
if (index != -1) {
warningListeners.remove(index);
warningLocales.remove(index);
if (warningListeners.size() == 0) {
warningListeners = null;
warningLocales = null;
}
}
}
/** {@collect.stats}
* Removes all currently registered
* <code>IIOWriteWarningListener</code> objects.
*
* <p> The default implementation sets the
* <code>warningListeners</code> and <code>warningLocales</code>
* instance variables to <code>null</code>.
*/
public void removeAllIIOWriteWarningListeners() {
this.warningListeners = null;
this.warningLocales = null;
}
/** {@collect.stats}
* Adds an <code>IIOWriteProgressListener</code> to the list of
* registered progress listeners. If <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an <code>IIOWriteProgressListener</code> to be
* registered.
*
* @see #removeIIOWriteProgressListener
*/
public void
addIIOWriteProgressListener(IIOWriteProgressListener listener) {
if (listener == null) {
return;
}
progressListeners = ImageReader.addToList(progressListeners, listener);
}
/** {@collect.stats}
* Removes an <code>IIOWriteProgressListener</code> from the list
* of registered progress listeners. If the listener was not
* previously registered, or if <code>listener</code> is
* <code>null</code>, no exception will be thrown and no action
* will be taken.
*
* @param listener an <code>IIOWriteProgressListener</code> to be
* deregistered.
*
* @see #addIIOWriteProgressListener
*/
public void
removeIIOWriteProgressListener(IIOWriteProgressListener listener) {
if (listener == null || progressListeners == null) {
return;
}
progressListeners =
ImageReader.removeFromList(progressListeners, listener);
}
/** {@collect.stats}
* Removes all currently registered
* <code>IIOWriteProgressListener</code> objects.
*
* <p> The default implementation sets the
* <code>progressListeners</code> instance variable to
* <code>null</code>.
*/
public void removeAllIIOWriteProgressListeners() {
this.progressListeners = null;
}
/** {@collect.stats}
* Broadcasts the start of an image write to all registered
* <code>IIOWriteProgressListener</code>s by calling their
* <code>imageStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image about to be written.
*/
protected void processImageStarted(int imageIndex) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.imageStarted(this, imageIndex);
}
}
/** {@collect.stats}
* Broadcasts the current percentage of image completion to all
* registered <code>IIOWriteProgressListener</code>s by calling
* their <code>imageProgress</code> method. Subclasses may use
* this method as a convenience.
*
* @param percentageDone the current percentage of completion,
* as a <code>float</code>.
*/
protected void processImageProgress(float percentageDone) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.imageProgress(this, percentageDone);
}
}
/** {@collect.stats}
* Broadcasts the completion of an image write to all registered
* <code>IIOWriteProgressListener</code>s by calling their
* <code>imageComplete</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processImageComplete() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.imageComplete(this);
}
}
/** {@collect.stats}
* Broadcasts the start of a thumbnail write to all registered
* <code>IIOWriteProgressListener</code>s by calling their
* <code>thumbnailStarted</code> method. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image associated with the
* thumbnail.
* @param thumbnailIndex the index of the thumbnail.
*/
protected void processThumbnailStarted(int imageIndex,
int thumbnailIndex) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.thumbnailStarted(this, imageIndex, thumbnailIndex);
}
}
/** {@collect.stats}
* Broadcasts the current percentage of thumbnail completion to
* all registered <code>IIOWriteProgressListener</code>s by calling
* their <code>thumbnailProgress</code> method. Subclasses may
* use this method as a convenience.
*
* @param percentageDone the current percentage of completion,
* as a <code>float</code>.
*/
protected void processThumbnailProgress(float percentageDone) {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.thumbnailProgress(this, percentageDone);
}
}
/** {@collect.stats}
* Broadcasts the completion of a thumbnail write to all registered
* <code>IIOWriteProgressListener</code>s by calling their
* <code>thumbnailComplete</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processThumbnailComplete() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.thumbnailComplete(this);
}
}
/** {@collect.stats}
* Broadcasts that the write has been aborted to all registered
* <code>IIOWriteProgressListener</code>s by calling their
* <code>writeAborted</code> method. Subclasses may use this
* method as a convenience.
*/
protected void processWriteAborted() {
if (progressListeners == null) {
return;
}
int numListeners = progressListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteProgressListener listener =
(IIOWriteProgressListener)progressListeners.get(i);
listener.writeAborted(this);
}
}
/** {@collect.stats}
* Broadcasts a warning message to all registered
* <code>IIOWriteWarningListener</code>s by calling their
* <code>warningOccurred</code> method. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image on which the warning
* occurred.
* @param warning the warning message.
*
* @exception IllegalArgumentException if <code>warning</code>
* is <code>null</code>.
*/
protected void processWarningOccurred(int imageIndex,
String warning) {
if (warningListeners == null) {
return;
}
if (warning == null) {
throw new IllegalArgumentException("warning == null!");
}
int numListeners = warningListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteWarningListener listener =
(IIOWriteWarningListener)warningListeners.get(i);
listener.warningOccurred(this, imageIndex, warning);
}
}
/** {@collect.stats}
* Broadcasts a localized warning message to all registered
* <code>IIOWriteWarningListener</code>s by calling their
* <code>warningOccurred</code> method with a string taken
* from a <code>ResourceBundle</code>. Subclasses may use this
* method as a convenience.
*
* @param imageIndex the index of the image on which the warning
* occurred.
* @param baseName the base name of a set of
* <code>ResourceBundle</code>s containing localized warning
* messages.
* @param keyword the keyword used to index the warning message
* within the set of <code>ResourceBundle</code>s.
*
* @exception IllegalArgumentException if <code>baseName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>keyword</code>
* is <code>null</code>.
* @exception IllegalArgumentException if no appropriate
* <code>ResourceBundle</code> may be located.
* @exception IllegalArgumentException if the named resource is
* not found in the located <code>ResourceBundle</code>.
* @exception IllegalArgumentException if the object retrieved
* from the <code>ResourceBundle</code> is not a
* <code>String</code>.
*/
protected void processWarningOccurred(int imageIndex,
String baseName,
String keyword) {
if (warningListeners == null) {
return;
}
if (baseName == null) {
throw new IllegalArgumentException("baseName == null!");
}
if (keyword == null) {
throw new IllegalArgumentException("keyword == null!");
}
int numListeners = warningListeners.size();
for (int i = 0; i < numListeners; i++) {
IIOWriteWarningListener listener =
(IIOWriteWarningListener)warningListeners.get(i);
Locale locale = (Locale)warningLocales.get(i);
if (locale == null) {
locale = Locale.getDefault();
}
/** {@collect.stats}
* If an applet supplies an implementation of ImageWriter and
* resource bundles, then the resource bundle will need to be
* accessed via the applet class loader. So first try the context
* class loader to locate the resource bundle.
* If that throws MissingResourceException, then try the
* system class loader.
*/
ClassLoader loader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
ResourceBundle bundle = null;
try {
bundle = ResourceBundle.getBundle(baseName, locale, loader);
} catch (MissingResourceException mre) {
try {
bundle = ResourceBundle.getBundle(baseName, locale);
} catch (MissingResourceException mre1) {
throw new IllegalArgumentException("Bundle not found!");
}
}
String warning = null;
try {
warning = bundle.getString(keyword);
} catch (ClassCastException cce) {
throw new IllegalArgumentException("Resource is not a String!");
} catch (MissingResourceException mre) {
throw new IllegalArgumentException("Resource is missing!");
}
listener.warningOccurred(this, imageIndex, warning);
}
}
// State management
/** {@collect.stats}
* Restores the <code>ImageWriter</code> to its initial state.
*
* <p> The default implementation calls
* <code>setOutput(null)</code>, <code>setLocale(null)</code>,
* <code>removeAllIIOWriteWarningListeners()</code>,
* <code>removeAllIIOWriteProgressListeners()</code>, and
* <code>clearAbortRequest</code>.
*/
public void reset() {
setOutput(null);
setLocale(null);
removeAllIIOWriteWarningListeners();
removeAllIIOWriteProgressListeners();
clearAbortRequest();
}
/** {@collect.stats}
* Allows any resources held by this object to be released. The
* result of calling any other method (other than
* <code>finalize</code>) subsequent to a call to this method
* is undefined.
*
* <p>It is important for applications to call this method when they
* know they will no longer be using this <code>ImageWriter</code>.
* Otherwise, the writer may continue to hold on to resources
* indefinitely.
*
* <p>The default implementation of this method in the superclass does
* nothing. Subclass implementations should ensure that all resources,
* especially native resources, are released.
*/
public void dispose() {
}
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/** {@collect.stats}
* A node in a directed graph. In addition to an arbitrary
* <code>Object</code> containing user data associated with the node,
* each node maintains a <code>Set</code>s of nodes which are pointed
* to by the current node (available from <code>getOutNodes</code>).
* The in-degree of the node (that is, number of nodes that point to
* the current node) may be queried.
*
*/
class DigraphNode implements Cloneable, Serializable {
/** {@collect.stats} The data associated with this node. */
protected Object data;
/** {@collect.stats}
* A <code>Set</code> of neighboring nodes pointed to by this
* node.
*/
protected Set outNodes = new HashSet();
/** {@collect.stats} The in-degree of the node. */
protected int inDegree = 0;
/** {@collect.stats}
* A <code>Set</code> of neighboring nodes that point to this
* node.
*/
private Set inNodes = new HashSet();
public DigraphNode(Object data) {
this.data = data;
}
/** {@collect.stats} Returns the <code>Object</code> referenced by this node. */
public Object getData() {
return data;
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing the nodes pointed
* to by this node.
*/
public Iterator getOutNodes() {
return outNodes.iterator();
}
/** {@collect.stats}
* Adds a directed edge to the graph. The outNodes list of this
* node is updated and the in-degree of the other node is incremented.
*
* @param node a <code>DigraphNode</code>.
*
* @return <code>true</code> if the node was not previously the
* target of an edge.
*/
public boolean addEdge(DigraphNode node) {
if (outNodes.contains(node)) {
return false;
}
outNodes.add(node);
node.inNodes.add(this);
node.incrementInDegree();
return true;
}
/** {@collect.stats}
* Returns <code>true</code> if an edge exists between this node
* and the given node.
*
* @param node a <code>DigraphNode</code>.
*
* @return <code>true</code> if the node is the target of an edge.
*/
public boolean hasEdge(DigraphNode node) {
return outNodes.contains(node);
}
/** {@collect.stats}
* Removes a directed edge from the graph. The outNodes list of this
* node is updated and the in-degree of the other node is decremented.
*
* @return <code>true</code> if the node was previously the target
* of an edge.
*/
public boolean removeEdge(DigraphNode node) {
if (!outNodes.contains(node)) {
return false;
}
outNodes.remove(node);
node.inNodes.remove(this);
node.decrementInDegree();
return true;
}
/** {@collect.stats}
* Removes this node from the graph, updating neighboring nodes
* appropriately.
*/
public void dispose() {
Object[] inNodesArray = inNodes.toArray();
for(int i=0; i<inNodesArray.length; i++) {
DigraphNode node = (DigraphNode) inNodesArray[i];
node.removeEdge(this);
}
Object[] outNodesArray = outNodes.toArray();
for(int i=0; i<outNodesArray.length; i++) {
DigraphNode node = (DigraphNode) outNodesArray[i];
removeEdge(node);
}
}
/** {@collect.stats} Returns the in-degree of this node. */
public int getInDegree() {
return inDegree;
}
/** {@collect.stats} Increments the in-degree of this node. */
private void incrementInDegree() {
++inDegree;
}
/** {@collect.stats} Decrements the in-degree of this node. */
private void decrementInDegree() {
--inDegree;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.File;
import java.io.IOException;
import javax.imageio.stream.ImageInputStream;
/** {@collect.stats}
* The service provider interface (SPI) for
* <code>ImageInputStream</code>s. For more information on service
* provider interfaces, see the class comment for the
* <code>IIORegistry</code> class.
*
* <p> This interface allows arbitrary objects to be "wrapped" by
* instances of <code>ImageInputStream</code>. For example,
* a particular <code>ImageInputStreamSpi</code> might allow
* a generic <code>InputStream</code> to be used as an input source;
* another might take input from a <code>URL</code>.
*
* <p> By treating the creation of <code>ImageInputStream</code>s as a
* pluggable service, it becomes possible to handle future input
* sources without changing the API. Also, high-performance
* implementations of <code>ImageInputStream</code> (for example,
* native implementations for a particular platform) can be installed
* and used transparently by applications.
*
* @see IIORegistry
* @see javax.imageio.stream.ImageInputStream
*
*/
public abstract class ImageInputStreamSpi extends IIOServiceProvider {
/** {@collect.stats}
* A <code>Class</code> object indicating the legal object type
* for use by the <code>createInputStreamInstance</code> method.
*/
protected Class<?> inputClass;
/** {@collect.stats}
* Constructs a blank <code>ImageInputStreamSpi</code>. It is up
* to the subclass to initialize instance variables and/or
* override method implementations in order to provide working
* versions of all methods.
*/
protected ImageInputStreamSpi() {
}
/** {@collect.stats}
* Constructs an <code>ImageInputStreamSpi</code> with a given set
* of values.
*
* @param vendorName the vendor name.
* @param version a version identifier.
* @param inputClass a <code>Class</code> object indicating the
* legal object type for use by the
* <code>createInputStreamInstance</code> method.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
*/
public ImageInputStreamSpi(String vendorName,
String version,
Class<?> inputClass) {
super(vendorName, version);
this.inputClass = inputClass;
}
/** {@collect.stats}
* Returns a <code>Class</code> object representing the class or
* interface type that must be implemented by an input source in
* order to be "wrapped" in an <code>ImageInputStream</code> via
* the <code>createInputStreamInstance</code> method.
*
* <p> Typical return values might include
* <code>InputStream.class</code> or <code>URL.class</code>, but
* any class may be used.
*
* @return a <code>Class</code> variable.
*
* @see #createInputStreamInstance(Object, boolean, File)
*/
public Class<?> getInputClass() {
return inputClass;
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageInputStream</code>
* implementation associated with this service provider can
* optionally make use of a cache file for improved performance
* and/or memory footrprint. If <code>false</code>, the value of
* the <code>useCache</code> argument to
* <code>createInputStreamInstance</code> will be ignored.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if a cache file can be used by the
* input streams created by this service provider.
*/
public boolean canUseCacheFile() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageInputStream</code>
* implementation associated with this service provider requires
* the use of a cache <code>File</code>. If <code>true</code>,
* the value of the <code>useCache</code> argument to
* <code>createInputStreamInstance</code> will be ignored.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if a cache file is needed by the
* input streams created by this service provider.
*/
public boolean needsCacheFile() {
return false;
}
/** {@collect.stats}
* Returns an instance of the <code>ImageInputStream</code>
* implementation associated with this service provider. If the
* use of a cache file is optional, the <code>useCache</code>
* parameter will be consulted. Where a cache is required, or
* not applicable, the value of <code>useCache</code> will be ignored.
*
* @param input an object of the class type returned by
* <code>getInputClass</code>.
* @param useCache a <code>boolean</code> indicating whether a
* cache file should be used, in cases where it is optional.
* @param cacheDir a <code>File</code> indicating where the
* cache file should be created, or <code>null</code> to use the
* system directory.
*
* @return an <code>ImageInputStream</code> instance.
*
* @exception IllegalArgumentException if <code>input</code> is
* not an instance of the correct class or is <code>null</code>.
* @exception IllegalArgumentException if a cache file is needed
* but <code>cacheDir</code> is non-<code>null</code> and is not a
* directory.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see #getInputClass
* @see #canUseCacheFile
* @see #needsCacheFile
*/
public abstract ImageInputStream
createInputStreamInstance(Object input,
boolean useCache,
File cacheDir) throws IOException;
/** {@collect.stats}
* Returns an instance of the <code>ImageInputStream</code>
* implementation associated with this service provider. A cache
* file will be created in the system-dependent default
* temporary-file directory, if needed.
*
* @param input an object of the class type returned by
* <code>getInputClass</code>.
*
* @return an <code>ImageInputStream</code> instance.
*
* @exception IllegalArgumentException if <code>input</code> is
* not an instance of the correct class or is <code>null</code>.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see #getInputClass()
*/
public ImageInputStream createInputStreamInstance(Object input)
throws IOException {
return createInputStreamInstance(input, true, null);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.ServiceLoader;
/** {@collect.stats}
* A registry for service provider instances.
*
* <p> A <i>service</i> is a well-known set of interfaces and (usually
* abstract) classes. A <i>service provider</i> is a specific
* implementation of a service. The classes in a provider typically
* implement the interface or subclass the class defined by the
* service itself.
*
* <p> Service providers are stored in one or more <i>categories</i>,
* each of which is defined by a class of interface (described by a
* <code>Class</code> object) that all of its members must implement.
* The set of categories may be changed dynamically.
*
* <p> Only a single instance of a given leaf class (that is, the
* actual class returned by <code>getClass()</code>, as opposed to any
* inherited classes or interfaces) may be registered. That is,
* suppose that the
* <code>com.mycompany.mypkg.GreenServiceProvider</code> class
* implements the <code>com.mycompany.mypkg.MyService</code>
* interface. If a <code>GreenServiceProvider</code> instance is
* registered, it will be stored in the category defined by the
* <code>MyService</code> class. If a new instance of
* <code>GreenServiceProvider</code> is registered, it will replace
* the previous instance. In practice, service provider objects are
* usually singletons so this behavior is appropriate.
*
* <p> To declare a service provider, a <code>services</code>
* subdirectory is placed within the <code>META-INF</code> directory
* that is present in every JAR file. This directory contains a file
* for each service provider interface that has one or more
* implementation classes present in the JAR file. For example, if
* the JAR file contained a class named
* <code>com.mycompany.mypkg.MyServiceImpl</code> which implements the
* <code>javax.someapi.SomeService</code> interface, the JAR file
* would contain a file named: <pre>
* META-INF/services/javax.someapi.SomeService </pre>
*
* containing the line:
*
* <pre>
* com.mycompany.mypkg.MyService
* </pre>
*
* <p> The service provider classes should be to be lightweight and
* quick to load. Implementations of these interfaces should avoid
* complex dependencies on other classes and on native code. The usual
* pattern for more complex services is to register a lightweight
* proxy for the heavyweight service.
*
* <p> An application may customize the contents of a registry as it
* sees fit, so long as it has the appropriate runtime permission.
*
* <p> For more details on declaring service providers, and the JAR
* format in general, see the <a
* href="../../../../technotes/guides/jar/jar.html">
* JAR File Specification</a>.
*
* @see RegisterableService
*
*/
public class ServiceRegistry {
// Class -> Registry
private Map categoryMap = new HashMap();
/** {@collect.stats}
* Constructs a <code>ServiceRegistry</code> instance with a
* set of categories taken from the <code>categories</code>
* argument.
*
* @param categories an <code>Iterator</code> containing
* <code>Class</code> objects to be used to define categories.
*
* @exception IllegalArgumentException if
* <code>categories</code> is <code>null</code>.
*/
public ServiceRegistry(Iterator<Class<?>> categories) {
if (categories == null) {
throw new IllegalArgumentException("categories == null!");
}
while (categories.hasNext()) {
Class category = (Class)categories.next();
SubRegistry reg = new SubRegistry(this, category);
categoryMap.put(category, reg);
}
}
// The following two methods expose functionality from
// sun.misc.Service. If that class is made public, they may be
// removed.
//
// The sun.misc.ServiceConfigurationError class may also be
// exposed, in which case the references to 'an
// <code>Error</code>' below should be changed to 'a
// <code>ServiceConfigurationError</code>'.
/** {@collect.stats}
* Searches for implementations of a particular service class
* using the given class loader.
*
* <p> This method transforms the name of the given service class
* into a provider-configuration filename as described in the
* class comment and then uses the <code>getResources</code>
* method of the given class loader to find all available files
* with that name. These files are then read and parsed to
* produce a list of provider-class names. The iterator that is
* returned uses the given class loader to look up and then
* instantiate each element of the list.
*
* <p> Because it is possible for extensions to be installed into
* a running Java virtual machine, this method may return
* different results each time it is invoked.
*
* @param providerClass a <code>Class</code>object indicating the
* class or interface of the service providers being detected.
*
* @param loader the class loader to be used to load
* provider-configuration files and instantiate provider classes,
* or <code>null</code> if the system class loader (or, failing that
* the bootstrap class loader) is to be used.
*
* @return An <code>Iterator</code> that yields provider objects
* for the given service, in some arbitrary order. The iterator
* will throw an <code>Error</code> if a provider-configuration
* file violates the specified format or if a provider class
* cannot be found and instantiated.
*
* @exception IllegalArgumentException if
* <code>providerClass</code> is <code>null</code>.
*/
public static <T> Iterator<T> lookupProviders(Class<T> providerClass,
ClassLoader loader)
{
if (providerClass == null) {
throw new IllegalArgumentException("providerClass == null!");
}
return ServiceLoader.load(providerClass, loader).iterator();
}
/** {@collect.stats}
* Locates and incrementally instantiates the available providers
* of a given service using the context class loader. This
* convenience method is equivalent to:
*
* <pre>
* ClassLoader cl = Thread.currentThread().getContextClassLoader();
* return Service.providers(service, cl);
* </pre>
*
* @param providerClass a <code>Class</code>object indicating the
* class or interface of the service providers being detected.
*
* @return An <code>Iterator</code> that yields provider objects
* for the given service, in some arbitrary order. The iterator
* will throw an <code>Error</code> if a provider-configuration
* file violates the specified format or if a provider class
* cannot be found and instantiated.
*
* @exception IllegalArgumentException if
* <code>providerClass</code> is <code>null</code>.
*/
public static <T> Iterator<T> lookupProviders(Class<T> providerClass) {
if (providerClass == null) {
throw new IllegalArgumentException("providerClass == null!");
}
return ServiceLoader.load(providerClass).iterator();
}
/** {@collect.stats}
* Returns an <code>Iterator</code> of <code>Class</code> objects
* indicating the current set of categories. The iterator will be
* empty if no categories exist.
*
* @return an <code>Iterator</code> containing
* <code>Class</code>objects.
*/
public Iterator<Class<?>> getCategories() {
Set keySet = categoryMap.keySet();
return keySet.iterator();
}
/** {@collect.stats}
* Returns an Iterator containing the subregistries to which the
* provider belongs.
*/
private Iterator getSubRegistries(Object provider) {
List l = new ArrayList();
Iterator iter = categoryMap.keySet().iterator();
while (iter.hasNext()) {
Class c = (Class)iter.next();
if (c.isAssignableFrom(provider.getClass())) {
l.add((SubRegistry)categoryMap.get(c));
}
}
return l.iterator();
}
/** {@collect.stats}
* Adds a service provider object to the registry. The provider
* is associated with the given category.
*
* <p> If <code>provider</code> implements the
* <code>RegisterableService</code> interface, its
* <code>onRegistration</code> method will be called. Its
* <code>onDeregistration</code> method will be called each time
* it is deregistered from a category, for example if a
* category is removed or the registry is garbage collected.
*
* @param provider the service provide object to be registered.
* @param category the category under which to register the
* provider.
*
* @return true if no provider of the same class was previously
* registered in the same category category.
*
* @exception IllegalArgumentException if <code>provider</code> is
* <code>null</code>.
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
* @exception ClassCastException if provider does not implement
* the <code>Class</code> defined by <code>category</code>.
*/
public <T> boolean registerServiceProvider(T provider,
Class<T> category) {
if (provider == null) {
throw new IllegalArgumentException("provider == null!");
}
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
if (!category.isAssignableFrom(provider.getClass())) {
throw new ClassCastException();
}
return reg.registerServiceProvider(provider);
}
/** {@collect.stats}
* Adds a service provider object to the registry. The provider
* is associated within each category present in the registry
* whose <code>Class</code> it implements.
*
* <p> If <code>provider</code> implements the
* <code>RegisterableService</code> interface, its
* <code>onRegistration</code> method will be called once for each
* category it is registered under. Its
* <code>onDeregistration</code> method will be called each time
* it is deregistered from a category or when the registry is
* finalized.
*
* @param provider the service provider object to be registered.
*
* @exception IllegalArgumentException if
* <code>provider</code> is <code>null</code>.
*/
public void registerServiceProvider(Object provider) {
if (provider == null) {
throw new IllegalArgumentException("provider == null!");
}
Iterator regs = getSubRegistries(provider);
while (regs.hasNext()) {
SubRegistry reg = (SubRegistry)regs.next();
reg.registerServiceProvider(provider);
}
}
/** {@collect.stats}
* Adds a set of service provider objects, taken from an
* <code>Iterator</code> to the registry. Each provider is
* associated within each category present in the registry whose
* <code>Class</code> it implements.
*
* <p> For each entry of <code>providers</code> that implements
* the <code>RegisterableService</code> interface, its
* <code>onRegistration</code> method will be called once for each
* category it is registered under. Its
* <code>onDeregistration</code> method will be called each time
* it is deregistered from a category or when the registry is
* finalized.
*
* @param providers an Iterator containing service provider
* objects to be registered.
*
* @exception IllegalArgumentException if <code>providers</code>
* is <code>null</code> or contains a <code>null</code> entry.
*/
public void registerServiceProviders(Iterator<?> providers) {
if (providers == null) {
throw new IllegalArgumentException("provider == null!");
}
while (providers.hasNext()) {
registerServiceProvider(providers.next());
}
}
/** {@collect.stats}
* Removes a service provider object from the given category. If
* the provider was not previously registered, nothing happens and
* <code>false</code> is returned. Otherwise, <code>true</code>
* is returned. If an object of the same class as
* <code>provider</code> but not equal (using <code>==</code>) to
* <code>provider</code> is registered, it will not be
* deregistered.
*
* <p> If <code>provider</code> implements the
* <code>RegisterableService</code> interface, its
* <code>onDeregistration</code> method will be called.
*
* @param provider the service provider object to be deregistered.
* @param category the category from which to deregister the
* provider.
*
* @return <code>true</code> if the provider was previously
* registered in the same category category,
* <code>false</code> otherwise.
*
* @exception IllegalArgumentException if <code>provider</code> is
* <code>null</code>.
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
* @exception ClassCastException if provider does not implement
* the class defined by <code>category</code>.
*/
public <T> boolean deregisterServiceProvider(T provider,
Class<T> category) {
if (provider == null) {
throw new IllegalArgumentException("provider == null!");
}
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
if (!category.isAssignableFrom(provider.getClass())) {
throw new ClassCastException();
}
return reg.deregisterServiceProvider(provider);
}
/** {@collect.stats}
* Removes a service provider object from all categories that
* contain it.
*
* @param provider the service provider object to be deregistered.
*
* @exception IllegalArgumentException if <code>provider</code> is
* <code>null</code>.
*/
public void deregisterServiceProvider(Object provider) {
if (provider == null) {
throw new IllegalArgumentException("provider == null!");
}
Iterator regs = getSubRegistries(provider);
while (regs.hasNext()) {
SubRegistry reg = (SubRegistry)regs.next();
reg.deregisterServiceProvider(provider);
}
}
/** {@collect.stats}
* Returns <code>true</code> if <code>provider</code> is currently
* registered.
*
* @param provider the service provider object to be queried.
*
* @return <code>true</code> if the given provider has been
* registered.
*
* @exception IllegalArgumentException if <code>provider</code> is
* <code>null</code>.
*/
public boolean contains(Object provider) {
if (provider == null) {
throw new IllegalArgumentException("provider == null!");
}
Iterator regs = getSubRegistries(provider);
while (regs.hasNext()) {
SubRegistry reg = (SubRegistry)regs.next();
if (reg.contains(provider)) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all registered
* service providers in the given category. If
* <code>useOrdering</code> is <code>false</code>, the iterator
* will return all of the server provider objects in an arbitrary
* order. Otherwise, the ordering will respect any pairwise
* orderings that have been set. If the graph of pairwise
* orderings contains cycles, any providers that belong to a cycle
* will not be returned.
*
* @param category the category to be retrieved from.
* @param useOrdering <code>true</code> if pairwise orderings
* should be taken account in ordering the returned objects.
*
* @return an <code>Iterator</code> containing service provider
* objects from the given category, possibly in order.
*
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
*/
public <T> Iterator<T> getServiceProviders(Class<T> category,
boolean useOrdering) {
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
return reg.getServiceProviders(useOrdering);
}
/** {@collect.stats}
* A simple filter interface used by
* <code>ServiceRegistry.getServiceProviders</code> to select
* providers matching an arbitrary criterion. Classes that
* implement this interface should be defined in order to make use
* of the <code>getServiceProviders</code> method of
* <code>ServiceRegistry</code> that takes a <code>Filter</code>.
*
* @see ServiceRegistry#getServiceProviders(Class, ServiceRegistry.Filter, boolean)
*/
public interface Filter {
/** {@collect.stats}
* Returns <code>true</code> if the given
* <code>provider</code> object matches the criterion defined
* by this <code>Filter</code>.
*
* @param provider a service provider <code>Object</code>.
*
* @return true if the provider matches the criterion.
*/
boolean filter(Object provider);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing service provider
* objects within a given category that satisfy a criterion
* imposed by the supplied <code>ServiceRegistry.Filter</code>
* object's <code>filter</code> method.
*
* <p> The <code>useOrdering</code> argument controls the
* ordering of the results using the same rules as
* <code>getServiceProviders(Class, boolean)</code>.
*
* @param category the category to be retrieved from.
* @param filter an instance of <code>ServiceRegistry.Filter</code>
* whose <code>filter</code> method will be invoked.
* @param useOrdering <code>true</code> if pairwise orderings
* should be taken account in ordering the returned objects.
*
* @return an <code>Iterator</code> containing service provider
* objects from the given category, possibly in order.
*
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
*/
public <T> Iterator<T> getServiceProviders(Class<T> category,
Filter filter,
boolean useOrdering) {
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
Iterator iter = getServiceProviders(category, useOrdering);
return new FilterIterator(iter, filter);
}
/** {@collect.stats}
* Returns the currently registered service provider object that
* is of the given class type. At most one object of a given
* class is allowed to be registered at any given time. If no
* registered object has the desired class type, <code>null</code>
* is returned.
*
* @param providerClass the <code>Class</code> of the desired
* service provider object.
*
* @return a currently registered service provider object with the
* desired <code>Class</code>type, or <code>null</code> is none is
* present.
*
* @exception IllegalArgumentException if <code>providerClass</code> is
* <code>null</code>.
*/
public <T> T getServiceProviderByClass(Class<T> providerClass) {
if (providerClass == null) {
throw new IllegalArgumentException("providerClass == null!");
}
Iterator iter = categoryMap.keySet().iterator();
while (iter.hasNext()) {
Class c = (Class)iter.next();
if (c.isAssignableFrom(providerClass)) {
SubRegistry reg = (SubRegistry)categoryMap.get(c);
T provider = reg.getServiceProviderByClass(providerClass);
if (provider != null) {
return provider;
}
}
}
return null;
}
/** {@collect.stats}
* Sets a pairwise ordering between two service provider objects
* within a given category. If one or both objects are not
* currently registered within the given category, or if the
* desired ordering is already set, nothing happens and
* <code>false</code> is returned. If the providers previously
* were ordered in the reverse direction, that ordering is
* removed.
*
* <p> The ordering will be used by the
* <code>getServiceProviders</code> methods when their
* <code>useOrdering</code> argument is <code>true</code>.
*
* @param category a <code>Class</code> object indicating the
* category under which the preference is to be established.
* @param firstProvider the preferred provider.
* @param secondProvider the provider to which
* <code>firstProvider</code> is preferred.
*
* @return <code>true</code> if a previously unset ordering
* was established.
*
* @exception IllegalArgumentException if either provider is
* <code>null</code> or they are the same object.
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
*/
public <T> boolean setOrdering(Class<T> category,
T firstProvider,
T secondProvider) {
if (firstProvider == null || secondProvider == null) {
throw new IllegalArgumentException("provider is null!");
}
if (firstProvider == secondProvider) {
throw new IllegalArgumentException("providers are the same!");
}
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
if (reg.contains(firstProvider) &&
reg.contains(secondProvider)) {
return reg.setOrdering(firstProvider, secondProvider);
}
return false;
}
/** {@collect.stats}
* Sets a pairwise ordering between two service provider objects
* within a given category. If one or both objects are not
* currently registered within the given category, or if no
* ordering is currently set between them, nothing happens
* and <code>false</code> is returned.
*
* <p> The ordering will be used by the
* <code>getServiceProviders</code> methods when their
* <code>useOrdering</code> argument is <code>true</code>.
*
* @param category a <code>Class</code> object indicating the
* category under which the preference is to be disestablished.
* @param firstProvider the formerly preferred provider.
* @param secondProvider the provider to which
* <code>firstProvider</code> was formerly preferred.
*
* @return <code>true</code> if a previously set ordering was
* disestablished.
*
* @exception IllegalArgumentException if either provider is
* <code>null</code> or they are the same object.
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
*/
public <T> boolean unsetOrdering(Class<T> category,
T firstProvider,
T secondProvider) {
if (firstProvider == null || secondProvider == null) {
throw new IllegalArgumentException("provider is null!");
}
if (firstProvider == secondProvider) {
throw new IllegalArgumentException("providers are the same!");
}
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
if (reg.contains(firstProvider) &&
reg.contains(secondProvider)) {
return reg.unsetOrdering(firstProvider, secondProvider);
}
return false;
}
/** {@collect.stats}
* Deregisters all service provider object currently registered
* under the given category.
*
* @param category the category to be emptied.
*
* @exception IllegalArgumentException if there is no category
* corresponding to <code>category</code>.
*/
public void deregisterAll(Class<?> category) {
SubRegistry reg = (SubRegistry)categoryMap.get(category);
if (reg == null) {
throw new IllegalArgumentException("category unknown!");
}
reg.clear();
}
/** {@collect.stats}
* Deregisters all currently registered service providers from all
* categories.
*/
public void deregisterAll() {
Iterator iter = categoryMap.values().iterator();
while (iter.hasNext()) {
SubRegistry reg = (SubRegistry)iter.next();
reg.clear();
}
}
/** {@collect.stats}
* Finalizes this object prior to garbage collection. The
* <code>deregisterAll</code> method is called to deregister all
* currently registered service providers. This method should not
* be called from application code.
*
* @exception Throwable if an error occurs during superclass
* finalization.
*/
public void finalize() throws Throwable {
deregisterAll();
super.finalize();
}
}
/** {@collect.stats}
* A portion of a registry dealing with a single superclass or
* interface.
*/
class SubRegistry {
ServiceRegistry registry;
Class category;
// Provider Objects organized by partial oridering
PartiallyOrderedSet poset = new PartiallyOrderedSet();
// Class -> Provider Object of that class
Map<Class<?>,Object> map = new HashMap();
public SubRegistry(ServiceRegistry registry, Class category) {
this.registry = registry;
this.category = category;
}
public boolean registerServiceProvider(Object provider) {
Object oprovider = map.get(provider.getClass());
boolean present = oprovider != null;
if (present) {
deregisterServiceProvider(oprovider);
}
map.put(provider.getClass(), provider);
poset.add(provider);
if (provider instanceof RegisterableService) {
RegisterableService rs = (RegisterableService)provider;
rs.onRegistration(registry, category);
}
return !present;
}
/** {@collect.stats}
* If the provider was not previously registered, do nothing.
*
* @return true if the provider was previously registered.
*/
public boolean deregisterServiceProvider(Object provider) {
Object oprovider = map.get(provider.getClass());
if (provider == oprovider) {
map.remove(provider.getClass());
poset.remove(provider);
if (provider instanceof RegisterableService) {
RegisterableService rs = (RegisterableService)provider;
rs.onDeregistration(registry, category);
}
return true;
}
return false;
}
public boolean contains(Object provider) {
Object oprovider = map.get(provider.getClass());
return oprovider == provider;
}
public boolean setOrdering(Object firstProvider,
Object secondProvider) {
return poset.setOrdering(firstProvider, secondProvider);
}
public boolean unsetOrdering(Object firstProvider,
Object secondProvider) {
return poset.unsetOrdering(firstProvider, secondProvider);
}
public Iterator getServiceProviders(boolean useOrdering) {
if (useOrdering) {
return poset.iterator();
} else {
return map.values().iterator();
}
}
public <T> T getServiceProviderByClass(Class<T> providerClass) {
return (T)map.get(providerClass);
}
public void clear() {
Iterator iter = map.values().iterator();
while (iter.hasNext()) {
Object provider = iter.next();
iter.remove();
if (provider instanceof RegisterableService) {
RegisterableService rs = (RegisterableService)provider;
rs.onDeregistration(registry, category);
}
}
poset.clear();
}
public void finalize() {
clear();
}
}
/** {@collect.stats}
* A class for wrapping <code>Iterators</code> with a filter function.
* This provides an iterator for a subset without duplication.
*/
class FilterIterator<T> implements Iterator<T> {
private Iterator<T> iter;
private ServiceRegistry.Filter filter;
private T next = null;
public FilterIterator(Iterator<T> iter,
ServiceRegistry.Filter filter) {
this.iter = iter;
this.filter = filter;
advance();
}
private void advance() {
while (iter.hasNext()) {
T elt = iter.next();
if (filter.filter(elt)) {
next = elt;
return;
}
}
next = null;
}
public boolean hasNext() {
return next != null;
}
public T next() {
if (next == null) {
throw new NoSuchElementException();
}
T o = next;
advance();
return o;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
/** {@collect.stats}
* A set of <code>Object</code>s with pairwise orderings between them.
* The <code>iterator</code> method provides the elements in
* topologically sorted order. Elements participating in a cycle
* are not returned.
*
* Unlike the <code>SortedSet</code> and <code>SortedMap</code>
* interfaces, which require their elements to implement the
* <code>Comparable</code> interface, this class receives ordering
* information via its <code>setOrdering</code> and
* <code>unsetPreference</code> methods. This difference is due to
* the fact that the relevant ordering between elements is unlikely to
* be inherent in the elements themselves; rather, it is set
* dynamically accoring to application policy. For example, in a
* service provider registry situation, an application might allow the
* user to set a preference order for service provider objects
* supplied by a trusted vendor over those supplied by another.
*
*/
class PartiallyOrderedSet extends AbstractSet {
// The topological sort (roughly) follows the algorithm described in
// Horowitz and Sahni, _Fundamentals of Data Structures_ (1976),
// p. 315.
// Maps Objects to DigraphNodes that contain them
private Map poNodes = new HashMap();
// The set of Objects
private Set nodes = poNodes.keySet();
/** {@collect.stats}
* Constructs a <code>PartiallyOrderedSet</code>.
*/
public PartiallyOrderedSet() {}
public int size() {
return nodes.size();
}
public boolean contains(Object o) {
return nodes.contains(o);
}
/** {@collect.stats}
* Returns an iterator over the elements contained in this
* collection, with an ordering that respects the orderings set
* by the <code>setOrdering</code> method.
*/
public Iterator iterator() {
return new PartialOrderIterator(poNodes.values().iterator());
}
/** {@collect.stats}
* Adds an <code>Object</code> to this
* <code>PartiallyOrderedSet</code>.
*/
public boolean add(Object o) {
if (nodes.contains(o)) {
return false;
}
DigraphNode node = new DigraphNode(o);
poNodes.put(o, node);
return true;
}
/** {@collect.stats}
* Removes an <code>Object</code> from this
* <code>PartiallyOrderedSet</code>.
*/
public boolean remove(Object o) {
DigraphNode node = (DigraphNode)poNodes.get(o);
if (node == null) {
return false;
}
poNodes.remove(o);
node.dispose();
return true;
}
public void clear() {
poNodes.clear();
}
/** {@collect.stats}
* Sets an ordering between two nodes. When an iterator is
* requested, the first node will appear earlier in the
* sequence than the second node. If a prior ordering existed
* between the nodes in the opposite order, it is removed.
*
* @return <code>true</code> if no prior ordering existed
* between the nodes, <code>false</code>otherwise.
*/
public boolean setOrdering(Object first, Object second) {
DigraphNode firstPONode =
(DigraphNode)poNodes.get(first);
DigraphNode secondPONode =
(DigraphNode)poNodes.get(second);
secondPONode.removeEdge(firstPONode);
return firstPONode.addEdge(secondPONode);
}
/** {@collect.stats}
* Removes any ordering between two nodes.
*
* @return true if a prior prefence existed between the nodes.
*/
public boolean unsetOrdering(Object first, Object second) {
DigraphNode firstPONode =
(DigraphNode)poNodes.get(first);
DigraphNode secondPONode =
(DigraphNode)poNodes.get(second);
return firstPONode.removeEdge(secondPONode) ||
secondPONode.removeEdge(firstPONode);
}
/** {@collect.stats}
* Returns <code>true</code> if an ordering exists between two
* nodes.
*/
public boolean hasOrdering(Object preferred, Object other) {
DigraphNode preferredPONode =
(DigraphNode)poNodes.get(preferred);
DigraphNode otherPONode =
(DigraphNode)poNodes.get(other);
return preferredPONode.hasEdge(otherPONode);
}
}
class PartialOrderIterator implements Iterator {
LinkedList zeroList = new LinkedList();
Map inDegrees = new HashMap(); // DigraphNode -> Integer
public PartialOrderIterator(Iterator iter) {
// Initialize scratch in-degree values, zero list
while (iter.hasNext()) {
DigraphNode node = (DigraphNode)iter.next();
int inDegree = node.getInDegree();
inDegrees.put(node, new Integer(inDegree));
// Add nodes with zero in-degree to the zero list
if (inDegree == 0) {
zeroList.add(node);
}
}
}
public boolean hasNext() {
return !zeroList.isEmpty();
}
public Object next() {
DigraphNode first = (DigraphNode)zeroList.removeFirst();
// For each out node of the output node, decrement its in-degree
Iterator outNodes = first.getOutNodes();
while (outNodes.hasNext()) {
DigraphNode node = (DigraphNode)outNodes.next();
int inDegree = ((Integer)inDegrees.get(node)).intValue() - 1;
inDegrees.put(node, new Integer(inDegree));
// If the in-degree has fallen to 0, place the node on the list
if (inDegree == 0) {
zeroList.add(node);
}
}
return first.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.util.Locale;
import javax.imageio.spi.RegisterableService;
import javax.imageio.spi.ServiceRegistry;
/** {@collect.stats}
* A superinterface for functionality common to all Image I/O service
* provider interfaces (SPIs). For more information on service
* provider classes, see the class comment for the
* <code>IIORegistry</code> class.
*
* @see IIORegistry
* @see javax.imageio.spi.ImageReaderSpi
* @see javax.imageio.spi.ImageWriterSpi
* @see javax.imageio.spi.ImageTranscoderSpi
* @see javax.imageio.spi.ImageInputStreamSpi
*
*/
public abstract class IIOServiceProvider implements RegisterableService {
/** {@collect.stats}
* A <code>String</code> to be returned from
* <code>getVendorName</code>, initially <code>null</code>.
* Constructors should set this to a non-<code>null</code> value.
*/
protected String vendorName;
/** {@collect.stats}
* A <code>String</code> to be returned from
* <code>getVersion</code>, initially null. Constructors should
* set this to a non-<code>null</code> value.
*/
protected String version;
/** {@collect.stats}
* Constructs an <code>IIOServiceProvider</code> with a given
* vendor name and version identifier.
*
* @param vendorName the vendor name.
* @param version a version identifier.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
*/
public IIOServiceProvider(String vendorName,
String version) {
if (vendorName == null) {
throw new IllegalArgumentException("vendorName == null!");
}
if (version == null) {
throw new IllegalArgumentException("version == null!");
}
this.vendorName = vendorName;
this.version = version;
}
/** {@collect.stats}
* Constructs a blank <code>IIOServiceProvider</code>. It is up
* to the subclass to initialize instance variables and/or
* override method implementations in order to ensure that the
* <code>getVendorName</code> and <code>getVersion</code> methods
* will return non-<code>null</code> values.
*/
public IIOServiceProvider() {
}
/** {@collect.stats}
* A callback that will be called exactly once after the Spi class
* has been instantiated and registered in a
* <code>ServiceRegistry</code>. This may be used to verify that
* the environment is suitable for this service, for example that
* native libraries can be loaded. If the service cannot function
* in the environment where it finds itself, it should deregister
* itself from the registry.
*
* <p> Only the registry should call this method.
*
* <p> The default implementation does nothing.
*
* @see ServiceRegistry#registerServiceProvider(Object provider)
*/
public void onRegistration(ServiceRegistry registry,
Class<?> category) {}
/** {@collect.stats}
* A callback that will be whenever the Spi class has been
* deregistered from a <code>ServiceRegistry</code>.
*
* <p> Only the registry should call this method.
*
* <p> The default implementation does nothing.
*
* @see ServiceRegistry#deregisterServiceProvider(Object provider)
*/
public void onDeregistration(ServiceRegistry registry,
Class<?> category) {}
/** {@collect.stats}
* Returns the name of the vendor responsible for creating this
* service provider and its associated implementation. Because
* the vendor name may be used to select a service provider,
* it is not localized.
*
* <p> The default implementation returns the value of the
* <code>vendorName</code> instance variable.
*
* @return a non-<code>null</code> <code>String</code> containing
* the name of the vendor.
*/
public String getVendorName() {
return vendorName;
}
/** {@collect.stats}
* Returns a string describing the version
* number of this service provider and its associated
* implementation. Because the version may be used by transcoders
* to identify the service providers they understand, this method
* is not localized.
*
* <p> The default implementation returns the value of the
* <code>version</code> instance variable.
*
* @return a non-<code>null</code> <code>String</code> containing
* the version of this service provider.
*/
public String getVersion() {
return version;
}
/** {@collect.stats}
* Returns a brief, human-readable description of this service
* provider and its associated implementation. The resulting
* string should be localized for the supplied
* <code>Locale</code>, if possible.
*
* @param locale a <code>Locale</code> for which the return value
* should be localized.
*
* @return a <code>String</code> containing a description of this
* service provider.
*/
public abstract String getDescription(Locale locale);
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.security.PrivilegedAction;
import java.security.AccessController;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Vector;
import com.sun.imageio.spi.FileImageInputStreamSpi;
import com.sun.imageio.spi.FileImageOutputStreamSpi;
import com.sun.imageio.spi.InputStreamImageInputStreamSpi;
import com.sun.imageio.spi.OutputStreamImageOutputStreamSpi;
import com.sun.imageio.spi.RAFImageInputStreamSpi;
import com.sun.imageio.spi.RAFImageOutputStreamSpi;
import com.sun.imageio.plugins.gif.GIFImageReaderSpi;
import com.sun.imageio.plugins.gif.GIFImageWriterSpi;
import com.sun.imageio.plugins.jpeg.JPEGImageReaderSpi;
import com.sun.imageio.plugins.jpeg.JPEGImageWriterSpi;
import com.sun.imageio.plugins.png.PNGImageReaderSpi;
import com.sun.imageio.plugins.png.PNGImageWriterSpi;
import com.sun.imageio.plugins.bmp.BMPImageReaderSpi;
import com.sun.imageio.plugins.bmp.BMPImageWriterSpi;
import com.sun.imageio.plugins.wbmp.WBMPImageReaderSpi;
import com.sun.imageio.plugins.wbmp.WBMPImageWriterSpi;
import sun.awt.AppContext;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
/** {@collect.stats}
* A registry for service provider instances. Service provider
* classes may be detected at run time by means of meta-information in
* the JAR files containing them. The intent is that it be relatively
* inexpensive to load and inspect all available service provider
* classes. These classes may them be used to locate and instantiate
* more heavyweight classes that will perform actual work, in this
* case instances of <code>ImageReader</code>,
* <code>ImageWriter</code>, <code>ImageTranscoder</code>,
* <code>ImageInputStream</code>, and <code>ImageOutputStream</code>.
*
* <p> Service providers found on the system classpath (<i>e.g.</i>,
* the <code>jre/lib/ext</code> directory in Sun's implementation of
* JDK) are automatically loaded as soon as this class is
* instantiated.
*
* <p> When the <code>registerApplicationClasspathSpis</code> method
* is called, service provider instances declared in the
* meta-information section of JAR files on the application class path
* are loaded. To declare a service provider, a <code>services</code>
* subdirectory is placed within the <code>META-INF</code> directory
* that is present in every JAR file. This directory contains a file
* for each service provider interface that has one or more
* implementation classes present in the JAR file. For example, if
* the JAR file contained a class named
* <code>com.mycompany.imageio.MyFormatReaderSpi</code> which
* implements the <code>ImageReaderSpi</code> interface, the JAR file
* would contain a file named:
*
* <pre>
* META-INF/services/javax.imageio.spi.ImageReaderSpi
* </pre>
*
* containing the line:
*
* <pre>
* com.mycompany.imageio.MyFormatReaderSpi
* </pre>
*
* <p> The service provider classes are intended to be lightweight
* and quick to load. Implementations of these interfaces
* should avoid complex dependencies on other classes and on
* native code.
*
* <p> It is also possible to manually add service providers not found
* automatically, as well as to remove those that are using the
* interfaces of the <code>ServiceRegistry</code> class. Thus
* the application may customize the contents of the registry as it
* sees fit.
*
* <p> For more details on declaring service providers, and the JAR
* format in general, see the <a
* href="{@docRoot}/../technotes/guides/jar/jar.html">
* JAR File Specification</a>.
*
*/
public final class IIORegistry extends ServiceRegistry {
/** {@collect.stats}
* A <code>Vector</code> containing the valid IIO registry
* categories (superinterfaces) to be used in the constructor.
*/
private static final Vector initialCategories = new Vector(5);
static {
initialCategories.add(ImageReaderSpi.class);
initialCategories.add(ImageWriterSpi.class);
initialCategories.add(ImageTranscoderSpi.class);
initialCategories.add(ImageInputStreamSpi.class);
initialCategories.add(ImageOutputStreamSpi.class);
}
/** {@collect.stats}
* Set up the valid service provider categories and automatically
* register all available service providers.
*
* <p> The constructor is private in order to prevent creation of
* additional instances.
*/
private IIORegistry() {
super(initialCategories.iterator());
registerStandardSpis();
registerApplicationClasspathSpis();
}
/** {@collect.stats}
* Returns the default <code>IIORegistry</code> instance used by
* the Image I/O API. This instance should be used for all
* registry functions.
*
* <p> Each <code>ThreadGroup</code> will receive its own
* instance; this allows different <code>Applet</code>s in the
* same browser (for example) to each have their own registry.
*
* @return the default registry for the current
* <code>ThreadGroup</code>.
*/
public static IIORegistry getDefaultInstance() {
AppContext context = AppContext.getAppContext();
IIORegistry registry =
(IIORegistry)context.get(IIORegistry.class);
if (registry == null) {
// Create an instance for this AppContext
registry = new IIORegistry();
context.put(IIORegistry.class, registry);
}
return registry;
}
private void registerStandardSpis() {
// Hardwire standard SPIs
registerServiceProvider(new GIFImageReaderSpi());
registerServiceProvider(new GIFImageWriterSpi());
registerServiceProvider(new BMPImageReaderSpi());
registerServiceProvider(new BMPImageWriterSpi());
registerServiceProvider(new WBMPImageReaderSpi());
registerServiceProvider(new WBMPImageWriterSpi());
registerServiceProvider(new PNGImageReaderSpi());
registerServiceProvider(new PNGImageWriterSpi());
registerServiceProvider(new JPEGImageReaderSpi());
registerServiceProvider(new JPEGImageWriterSpi());
registerServiceProvider(new FileImageInputStreamSpi());
registerServiceProvider(new FileImageOutputStreamSpi());
registerServiceProvider(new InputStreamImageInputStreamSpi());
registerServiceProvider(new OutputStreamImageOutputStreamSpi());
registerServiceProvider(new RAFImageInputStreamSpi());
registerServiceProvider(new RAFImageOutputStreamSpi());
registerInstalledProviders();
}
/** {@collect.stats}
* Registers all available service providers found on the
* application class path, using the default
* <code>ClassLoader</code>. This method is typically invoked by
* the <code>ImageIO.scanForPlugins</code> method.
*
* @see javax.imageio.ImageIO#scanForPlugins
* @see ClassLoader#getResources
*/
public void registerApplicationClasspathSpis() {
// FIX: load only from application classpath
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Iterator categories = getCategories();
while (categories.hasNext()) {
Class<IIOServiceProvider> c = (Class)categories.next();
Iterator<IIOServiceProvider> riter =
ServiceLoader.load(c, loader).iterator();
while (riter.hasNext()) {
try {
// Note that the next() call is required to be inside
// the try/catch block; see 6342404.
IIOServiceProvider r = riter.next();
registerServiceProvider(r);
} catch (ServiceConfigurationError err) {
if (System.getSecurityManager() != null) {
// In the applet case, we will catch the error so
// registration of other plugins can proceed
err.printStackTrace();
} else {
// In the application case, we will throw the
// error to indicate app/system misconfiguration
throw err;
}
}
}
}
}
private void registerInstalledProviders() {
/*
We need load installed providers from lib/ext
directory in the privileged mode in order to
be able read corresponding jar files even if
file read capability is restricted (like the
applet context case).
*/
PrivilegedAction doRegistration =
new PrivilegedAction() {
public Object run() {
Iterator categories = getCategories();
while (categories.hasNext()) {
Class<IIOServiceProvider> c = (Class)categories.next();
for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) {
registerServiceProvider(p);
}
}
return this;
}
};
AccessController.doPrivileged(doRegistration);
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
/** {@collect.stats}
* An optional interface that may be provided by service provider
* objects that will be registered with a
* <code>ServiceRegistry</code>. If this interface is present,
* notification of registration and deregistration will be performed.
*
* @see ServiceRegistry
*
*/
public interface RegisterableService {
/** {@collect.stats}
* Called when an object implementing this interface is added to
* the given <code>category</code> of the given
* <code>registry</code>. The object may already be registered
* under another category or categories.
*
* @param registry a <code>ServiceRegistry</code> where this
* object has been registered.
* @param category a <code>Class</code> object indicating the
* registry category under which this object has been registered.
*/
void onRegistration(ServiceRegistry registry, Class<?> category);
/** {@collect.stats}
* Called when an object implementing this interface is removed
* from the given <code>category</code> of the given
* <code>registry</code>. The object may still be registered
* under another category or categories.
*
* @param registry a <code>ServiceRegistry</code> from which this
* object is being (wholly or partially) deregistered.
* @param category a <code>Class</code> object indicating the
* registry category from which this object is being deregistered.
*/
void onDeregistration(ServiceRegistry registry, Class<?> category);
}
|
Java
|
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.awt.image.RenderedImage;
import java.io.IOException;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
/** {@collect.stats}
* The service provider interface (SPI) for <code>ImageWriter</code>s.
* For more information on service provider classes, see the class comment
* for the <code>IIORegistry</code> class.
*
* <p> Each <code>ImageWriterSpi</code> provides several types of information
* about the <code>ImageWriter</code> class with which it is associated.
*
* <p> The name of the vendor who defined the SPI class and a
* brief description of the class are available via the
* <code>getVendorName</code>, <code>getDescription</code>,
* and <code>getVersion</code> methods.
* These methods may be internationalized to provide locale-specific
* output. These methods are intended mainly to provide short,
* human-writable information that might be used to organize a pop-up
* menu or other list.
*
* <p> Lists of format names, file suffixes, and MIME types associated
* with the service may be obtained by means of the
* <code>getFormatNames</code>, <code>getFileSuffixes</code>, and
* <code>getMIMEType</code> methods. These methods may be used to
* identify candidate <code>ImageWriter</code>s for writing a
* particular file or stream based on manual format selection, file
* naming, or MIME associations.
*
* <p> A more reliable way to determine which <code>ImageWriter</code>s
* are likely to be able to parse a particular data stream is provided
* by the <code>canEncodeImage</code> method. This methods allows the
* service provider to inspect the actual image contents.
*
* <p> Finally, an instance of the <code>ImageWriter</code> class
* associated with this service provider may be obtained by calling
* the <code>createWriterInstance</code> method. Any heavyweight
* initialization, such as the loading of native libraries or creation
* of large tables, should be deferred at least until the first
* invocation of this method.
*
* @see IIORegistry
* @see javax.imageio.ImageTypeSpecifier
* @see javax.imageio.ImageWriter
*
*/
public abstract class ImageWriterSpi extends ImageReaderWriterSpi {
/** {@collect.stats}
* A single-element array, initially containing
* <code>ImageInputStream.class</code>, to be returned from
* <code>getInputTypes</code>.
*/
public static final Class[] STANDARD_OUTPUT_TYPE =
{ ImageOutputStream.class };
/** {@collect.stats}
* An array of <code>Class</code> objects to be returned from
* <code>getOutputTypes</code>, initially <code>null</code>.
*/
protected Class[] outputTypes = null;
/** {@collect.stats}
* An array of strings to be returned from
* <code>getImageReaderSpiNames</code>, initially
* <code>null</code>.
*/
protected String[] readerSpiNames = null;
/** {@collect.stats}
* The <code>Class</code> of the writer, initially
* <code>null</code>.
*/
private Class writerClass = null;
/** {@collect.stats}
* Constructs a blank <code>ImageWriterSpi</code>. It is up to
* the subclass to initialize instance variables and/or override
* method implementations in order to provide working versions of
* all methods.
*/
protected ImageWriterSpi() {
}
/** {@collect.stats}
* Constructs an <code>ImageWriterSpi</code> with a given
* set of values.
*
* @param vendorName the vendor name, as a non-<code>null</code>
* <code>String</code>.
* @param version a version identifier, as a non-<code>null</code>
* <code>String</code>.
* @param names a non-<code>null</code> array of
* <code>String</code>s indicating the format names. At least one
* entry must be present.
* @param suffixes an array of <code>String</code>s indicating the
* common file suffixes. If no suffixes are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param MIMETypes an array of <code>String</code>s indicating
* the format's MIME types. If no suffixes are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param writerClassName the fully-qualified name of the
* associated <code>ImageWriterSpi</code> class, as a
* non-<code>null</code> <code>String</code>.
* @param outputTypes an array of <code>Class</code> objects of
* length at least 1 indicating the legal output types.
* @param readerSpiNames an array <code>String</code>s of length
* at least 1 naming the classes of all associated
* <code>ImageReader</code>s, or <code>null</code>. An array of
* length 0 is normalized to <code>null</code>.
* @param supportsStandardStreamMetadataFormat a
* <code>boolean</code> that indicates whether a stream metadata
* object can use trees described by the standard metadata format.
* @param nativeStreamMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeStreamMetadataFormatName</code>.
* @param nativeStreamMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeStreamMetadataFormat</code>.
* @param extraStreamMetadataFormatNames an array of
* <code>String</code>s, or <code>null</code>, to be returned from
* <code>getExtraStreamMetadataFormatNames</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param extraStreamMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getStreamMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param supportsStandardImageMetadataFormat a
* <code>boolean</code> that indicates whether an image metadata
* object can use trees described by the standard metadata format.
* @param nativeImageMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeImageMetadataFormatName</code>.
* @param nativeImageMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeImageMetadataFormat</code>.
* @param extraImageMetadataFormatNames an array of
* <code>String</code>s to be returned from
* <code>getExtraImageMetadataFormatNames</code>. An array of length 0
* is normalized to <code>null</code>.
* @param extraImageMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getImageMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>names</code>
* is <code>null</code> or has length 0.
* @exception IllegalArgumentException if <code>writerClassName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>outputTypes</code>
* is <code>null</code> or has length 0.
*/
public ImageWriterSpi(String vendorName,
String version,
String[] names,
String[] suffixes,
String[] MIMETypes,
String writerClassName,
Class[] outputTypes,
String[] readerSpiNames,
boolean supportsStandardStreamMetadataFormat,
String nativeStreamMetadataFormatName,
String nativeStreamMetadataFormatClassName,
String[] extraStreamMetadataFormatNames,
String[] extraStreamMetadataFormatClassNames,
boolean supportsStandardImageMetadataFormat,
String nativeImageMetadataFormatName,
String nativeImageMetadataFormatClassName,
String[] extraImageMetadataFormatNames,
String[] extraImageMetadataFormatClassNames) {
super(vendorName, version,
names, suffixes, MIMETypes, writerClassName,
supportsStandardStreamMetadataFormat,
nativeStreamMetadataFormatName,
nativeStreamMetadataFormatClassName,
extraStreamMetadataFormatNames,
extraStreamMetadataFormatClassNames,
supportsStandardImageMetadataFormat,
nativeImageMetadataFormatName,
nativeImageMetadataFormatClassName,
extraImageMetadataFormatNames,
extraImageMetadataFormatClassNames);
if (outputTypes == null) {
throw new IllegalArgumentException
("outputTypes == null!");
}
if (outputTypes.length == 0) {
throw new IllegalArgumentException
("outputTypes.length == 0!");
}
this.outputTypes = (outputTypes == STANDARD_OUTPUT_TYPE) ?
new Class<?>[] { ImageOutputStream.class } :
outputTypes.clone();
// If length == 0, leave it null
if (readerSpiNames != null && readerSpiNames.length > 0) {
this.readerSpiNames = (String[])readerSpiNames.clone();
}
}
/** {@collect.stats}
* Returns <code>true</code> if the format that this writer
* outputs preserves pixel data bit-accurately. The default
* implementation returns <code>true</code>.
*
* @return <code>true</code> if the format preserves full pixel
* accuracy.
*/
public boolean isFormatLossless() {
return true;
}
/** {@collect.stats}
* Returns an array of <code>Class</code> objects indicating what
* types of objects may be used as arguments to the writer's
* <code>setOutput</code> method.
*
* <p> For most writers, which only output to an
* <code>ImageOutputStream</code>, a single-element array
* containing <code>ImageOutputStream.class</code> should be
* returned.
*
* @return a non-<code>null</code> array of
* <code>Class</code>objects of length at least 1.
*/
public Class[] getOutputTypes() {
return (Class[])outputTypes.clone();
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageWriter</code>
* implementation associated with this service provider is able to
* encode an image with the given layout. The layout
* (<i>i.e.</i>, the image's <code>SampleModel</code> and
* <code>ColorModel</code>) is described by an
* <code>ImageTypeSpecifier</code> object.
*
* <p> A return value of <code>true</code> is not an absolute
* guarantee of successful encoding; the encoding process may still
* produce errors due to factors such as I/O errors, inconsistent
* or malformed data structures, etc. The intent is that a
* reasonable inspection of the basic structure of the image be
* performed in order to determine if it is within the scope of
* the encoding format. For example, a service provider for a
* format that can only encode greyscale would return
* <code>false</code> if handed an RGB <code>BufferedImage</code>.
* Similarly, a service provider for a format that can encode
* 8-bit RGB imagery might refuse to encode an image with an
* associated alpha channel.
*
* <p> Different <code>ImageWriter</code>s, and thus service
* providers, may choose to be more or less strict. For example,
* they might accept an image with premultiplied alpha even though
* it will have to be divided out of each pixel, at some loss of
* precision, in order to be stored.
*
* @param type an <code>ImageTypeSpecifier</code> specifying the
* layout of the image to be written.
*
* @return <code>true</code> if this writer is likely to be able
* to encode images with the given layout.
*
* @exception IllegalArgumentException if <code>type</code>
* is <code>null</code>.
*/
public abstract boolean canEncodeImage(ImageTypeSpecifier type);
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageWriter</code>
* implementation associated with this service provider is able to
* encode the given <code>RenderedImage</code> instance. Note
* that this includes instances of
* <code>java.awt.image.BufferedImage</code>.
*
* <p> See the discussion for
* <code>canEncodeImage(ImageTypeSpecifier)</code> for information
* on the semantics of this method.
*
* @param im an instance of <code>RenderedImage</code> to be encoded.
*
* @return <code>true</code> if this writer is likely to be able
* to encode this image.
*
* @exception IllegalArgumentException if <code>im</code>
* is <code>null</code>.
*/
public boolean canEncodeImage(RenderedImage im) {
return canEncodeImage(ImageTypeSpecifier.createFromRenderedImage(im));
}
/** {@collect.stats}
* Returns an instance of the <code>ImageWriter</code>
* implementation associated with this service provider.
* The returned object will initially be in an initial state as if
* its <code>reset</code> method had been called.
*
* <p> The default implementation simply returns
* <code>createWriterInstance(null)</code>.
*
* @return an <code>ImageWriter</code> instance.
*
* @exception IOException if an error occurs during loading,
* or initialization of the writer class, or during instantiation
* or initialization of the writer object.
*/
public ImageWriter createWriterInstance() throws IOException {
return createWriterInstance(null);
}
/** {@collect.stats}
* Returns an instance of the <code>ImageWriter</code>
* implementation associated with this service provider.
* The returned object will initially be in an initial state
* as if its <code>reset</code> method had been called.
*
* <p> An <code>Object</code> may be supplied to the plug-in at
* construction time. The nature of the object is entirely
* plug-in specific.
*
* <p> Typically, a plug-in will implement this method using code
* such as <code>return new MyImageWriter(this)</code>.
*
* @param extension a plug-in specific extension object, which may
* be <code>null</code>.
*
* @return an <code>ImageWriter</code> instance.
*
* @exception IOException if the attempt to instantiate
* the writer fails.
* @exception IllegalArgumentException if the
* <code>ImageWriter</code>'s constructor throws an
* <code>IllegalArgumentException</code> to indicate that the
* extension object is unsuitable.
*/
public abstract ImageWriter createWriterInstance(Object extension)
throws IOException;
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageWriter</code> object
* passed in is an instance of the <code>ImageWriter</code>
* associated with this service provider.
*
* @param writer an <code>ImageWriter</code> instance.
*
* @return <code>true</code> if <code>writer</code> is recognized
*
* @exception IllegalArgumentException if <code>writer</code> is
* <code>null</code>.
*/
public boolean isOwnWriter(ImageWriter writer) {
if (writer == null) {
throw new IllegalArgumentException("writer == null!");
}
String name = writer.getClass().getName();
return name.equals(pluginClassName);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing all the
* fully qualified names of all the <code>ImageReaderSpi</code>
* classes that can understand the internal metadata
* representation used by the <code>ImageWriter</code> associated
* with this service provider, or <code>null</code> if there are
* no such <code>ImageReaders</code> specified. If a
* non-<code>null</code> value is returned, it must have non-zero
* length.
*
* <p> The first item in the array must be the name of the service
* provider for the "preferred" reader, as it will be used to
* instantiate the <code>ImageReader</code> returned by
* <code>ImageIO.getImageReader(ImageWriter)</code>.
*
* <p> This mechanism may be used to obtain
* <code>ImageReaders</code> that will generated non-pixel
* meta-data (see <code>IIOExtraDataInfo</code>) in a structure
* understood by an <code>ImageWriter</code>. By reading the
* image and obtaining this data from one of the
* <code>ImageReaders</code> obtained with this method and passing
* it on to the <code>ImageWriter</code>, a client program can
* read an image, modify it in some way, and write it back out
* preserving all meta-data, without having to understand anything
* about the internal structure of the meta-data, or even about
* the image format.
*
* @return an array of <code>String</code>s of length at least 1
* containing names of <code>ImageReaderSpi</code>s, or
* <code>null</code>.
*
* @see javax.imageio.ImageIO#getImageReader(ImageWriter)
* @see ImageReaderSpi#getImageWriterSpiNames()
*/
public String[] getImageReaderSpiNames() {
return readerSpiNames == null ?
null : (String[])readerSpiNames.clone();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.File;
import java.io.IOException;
import javax.imageio.stream.ImageOutputStream;
/** {@collect.stats}
* The service provider interface (SPI) for
* <code>ImageOutputStream</code>s. For more information on service
* provider interfaces, see the class comment for the
* <code>IIORegistry</code> class.
*
* <p> This interface allows arbitrary objects to be "wrapped" by
* instances of <code>ImageOutputStream</code>. For example, a
* particular <code>ImageOutputStreamSpi</code> might allow a generic
* <code>OutputStream</code> to be used as a destination; another
* might output to a <code>File</code> or to a device such as a serial
* port.
*
* <p> By treating the creation of <code>ImageOutputStream</code>s as
* a pluggable service, it becomes possible to handle future output
* destinations without changing the API. Also, high-performance
* implementations of <code>ImageOutputStream</code> (for example,
* native implementations for a particular platform) can be installed
* and used transparently by applications.
*
* @see IIORegistry
* @see javax.imageio.stream.ImageOutputStream
*
*/
public abstract class ImageOutputStreamSpi extends IIOServiceProvider {
/** {@collect.stats}
* A <code>Class</code> object indicating the legal object type
* for use by the <code>createInputStreamInstance</code> method.
*/
protected Class<?> outputClass;
/** {@collect.stats}
* Constructs a blank <code>ImageOutputStreamSpi</code>. It is up
* to the subclass to initialize instance variables and/or
* override method implementations in order to provide working
* versions of all methods.
*/
protected ImageOutputStreamSpi() {
}
/** {@collect.stats}
* Constructs an <code>ImageOutputStreamSpi</code> with a given
* set of values.
*
* @param vendorName the vendor name.
* @param version a version identifier.
* @param outputClass a <code>Class</code> object indicating the
* legal object type for use by the
* <code>createOutputStreamInstance</code> method.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
*/
public ImageOutputStreamSpi(String vendorName,
String version,
Class<?> outputClass) {
super(vendorName, version);
this.outputClass = outputClass;
}
/** {@collect.stats}
* Returns a <code>Class</code> object representing the class or
* interface type that must be implemented by an output
* destination in order to be "wrapped" in an
* <code>ImageOutputStream</code> via the
* <code>createOutputStreamInstance</code> method.
*
* <p> Typical return values might include
* <code>OutputStream.class</code> or <code>File.class</code>, but
* any class may be used.
*
* @return a <code>Class</code> variable.
*
* @see #createOutputStreamInstance(Object, boolean, File)
*/
public Class<?> getOutputClass() {
return outputClass;
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageOutputStream</code>
* implementation associated with this service provider can
* optionally make use of a cache <code>File</code> for improved
* performance and/or memory footrprint. If <code>false</code>,
* the value of the <code>cacheFile</code> argument to
* <code>createOutputStreamInstance</code> will be ignored.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if a cache file can be used by the
* output streams created by this service provider.
*/
public boolean canUseCacheFile() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageOutputStream</code>
* implementation associated with this service provider requires
* the use of a cache <code>File</code>.
*
* <p> The default implementation returns <code>false</code>.
*
* @return <code>true</code> if a cache file is needed by the
* output streams created by this service provider.
*/
public boolean needsCacheFile() {
return false;
}
/** {@collect.stats}
* Returns an instance of the <code>ImageOutputStream</code>
* implementation associated with this service provider. If the
* use of a cache file is optional, the <code>useCache</code>
* parameter will be consulted. Where a cache is required, or
* not applicable, the value of <code>useCache</code> will be ignored.
*
* @param output an object of the class type returned by
* <code>getOutputClass</code>.
* @param useCache a <code>boolean</code> indicating whether a
* cache file should be used, in cases where it is optional.
* @param cacheDir a <code>File</code> indicating where the
* cache file should be created, or <code>null</code> to use the
* system directory.
*
* @return an <code>ImageOutputStream</code> instance.
*
* @exception IllegalArgumentException if <code>output</code> is
* not an instance of the correct class or is <code>null</code>.
* @exception IllegalArgumentException if a cache file is needed,
* but <code>cacheDir</code> is non-<code>null</code> and is not a
* directory.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see #getOutputClass
*/
public abstract
ImageOutputStream createOutputStreamInstance(Object output,
boolean useCache,
File cacheDir)
throws IOException;
/** {@collect.stats}
* Returns an instance of the <code>ImageOutputStream</code>
* implementation associated with this service provider. A cache
* file will be created in the system-dependent default
* temporary-file directory, if needed.
*
* @param output an object of the class type returned by
* <code>getOutputClass</code>.
*
* @return an <code>ImageOutputStream</code> instance.
*
* @exception IllegalArgumentException if <code>output</code> is
* not an instance of the correct class or is <code>null</code>.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see #getOutputClass()
*/
public ImageOutputStream createOutputStreamInstance(Object output)
throws IOException {
return createOutputStreamInstance(output, true, null);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.IOException;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
/** {@collect.stats}
* The service provider interface (SPI) for <code>ImageReader</code>s.
* For more information on service provider classes, see the class comment
* for the <code>IIORegistry</code> class.
*
* <p> Each <code>ImageReaderSpi</code> provides several types of information
* about the <code>ImageReader</code> class with which it is associated.
*
* <p> The name of the vendor who defined the SPI class and a
* brief description of the class are available via the
* <code>getVendorName</code>, <code>getDescription</code>,
* and <code>getVersion</code> methods.
* These methods may be internationalized to provide locale-specific
* output. These methods are intended mainly to provide short,
* human-readable information that might be used to organize a pop-up
* menu or other list.
*
* <p> Lists of format names, file suffixes, and MIME types associated
* with the service may be obtained by means of the
* <code>getFormatNames</code>, <code>getFileSuffixes</code>, and
* <code>getMIMETypes</code> methods. These methods may be used to
* identify candidate <code>ImageReader</code>s for decoding a
* particular file or stream based on manual format selection, file
* naming, or MIME associations (for example, when accessing a file
* over HTTP or as an email attachment).
*
* <p> A more reliable way to determine which <code>ImageReader</code>s
* are likely to be able to parse a particular data stream is provided
* by the <code>canDecodeInput</code> method. This methods allows the
* service provider to inspect the actual stream contents.
*
* <p> Finally, an instance of the <code>ImageReader</code> class
* associated with this service provider may be obtained by calling
* the <code>createReaderInstance</code> method. Any heavyweight
* initialization, such as the loading of native libraries or creation
* of large tables, should be deferred at least until the first
* invocation of this method.
*
* @see IIORegistry
* @see javax.imageio.ImageReader
*
*/
public abstract class ImageReaderSpi extends ImageReaderWriterSpi {
/** {@collect.stats}
* A single-element array, initially containing
* <code>ImageInputStream.class</code>, to be returned from
* <code>getInputTypes</code>.
*/
public static final Class[] STANDARD_INPUT_TYPE =
{ ImageInputStream.class };
/** {@collect.stats}
* An array of <code>Class</code> objects to be returned from
* <code>getInputTypes</code>, initially <code>null</code>.
*/
protected Class[] inputTypes = null;
/** {@collect.stats}
* An array of strings to be returned from
* <code>getImageWriterSpiNames</code>, initially
* <code>null</code>.
*/
protected String[] writerSpiNames = null;
/** {@collect.stats}
* The <code>Class</code> of the reader, initially
* <code>null</code>.
*/
private Class readerClass = null;
/** {@collect.stats}
* Constructs a blank <code>ImageReaderSpi</code>. It is up to
* the subclass to initialize instance variables and/or override
* method implementations in order to provide working versions of
* all methods.
*/
protected ImageReaderSpi() {
}
/** {@collect.stats}
* Constructs an <code>ImageReaderSpi</code> with a given
* set of values.
*
* @param vendorName the vendor name, as a non-<code>null</code>
* <code>String</code>.
* @param version a version identifier, as a non-<code>null</code>
* <code>String</code>.
* @param names a non-<code>null</code> array of
* <code>String</code>s indicating the format names. At least one
* entry must be present.
* @param suffixes an array of <code>String</code>s indicating the
* common file suffixes. If no suffixes are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param MIMETypes an array of <code>String</code>s indicating
* the format's MIME types. If no MIME types are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param readerClassName the fully-qualified name of the
* associated <code>ImageReader</code> class, as a
* non-<code>null</code> <code>String</code>.
* @param inputTypes a non-<code>null</code> array of
* <code>Class</code> objects of length at least 1 indicating the
* legal input types.
* @param writerSpiNames an array <code>String</code>s naming the
* classes of all associated <code>ImageWriter</code>s, or
* <code>null</code>. An array of length 0 is normalized to
* <code>null</code>.
* @param supportsStandardStreamMetadataFormat a
* <code>boolean</code> that indicates whether a stream metadata
* object can use trees described by the standard metadata format.
* @param nativeStreamMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeStreamMetadataFormatName</code>.
* @param nativeStreamMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeStreamMetadataFormat</code>.
* @param extraStreamMetadataFormatNames an array of
* <code>String</code>s, or <code>null</code>, to be returned from
* <code>getExtraStreamMetadataFormatNames</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param extraStreamMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getStreamMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param supportsStandardImageMetadataFormat a
* <code>boolean</code> that indicates whether an image metadata
* object can use trees described by the standard metadata format.
* @param nativeImageMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeImageMetadataFormatName</code>.
* @param nativeImageMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeImageMetadataFormat</code>.
* @param extraImageMetadataFormatNames an array of
* <code>String</code>s to be returned from
* <code>getExtraImageMetadataFormatNames</code>. An array of length 0
* is normalized to <code>null</code>.
* @param extraImageMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getImageMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>names</code>
* is <code>null</code> or has length 0.
* @exception IllegalArgumentException if <code>readerClassName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>inputTypes</code>
* is <code>null</code> or has length 0.
*/
public ImageReaderSpi(String vendorName,
String version,
String[] names,
String[] suffixes,
String[] MIMETypes,
String readerClassName,
Class[] inputTypes,
String[] writerSpiNames,
boolean supportsStandardStreamMetadataFormat,
String nativeStreamMetadataFormatName,
String nativeStreamMetadataFormatClassName,
String[] extraStreamMetadataFormatNames,
String[] extraStreamMetadataFormatClassNames,
boolean supportsStandardImageMetadataFormat,
String nativeImageMetadataFormatName,
String nativeImageMetadataFormatClassName,
String[] extraImageMetadataFormatNames,
String[] extraImageMetadataFormatClassNames) {
super(vendorName, version,
names, suffixes, MIMETypes, readerClassName,
supportsStandardStreamMetadataFormat,
nativeStreamMetadataFormatName,
nativeStreamMetadataFormatClassName,
extraStreamMetadataFormatNames,
extraStreamMetadataFormatClassNames,
supportsStandardImageMetadataFormat,
nativeImageMetadataFormatName,
nativeImageMetadataFormatClassName,
extraImageMetadataFormatNames,
extraImageMetadataFormatClassNames);
if (inputTypes == null) {
throw new IllegalArgumentException
("inputTypes == null!");
}
if (inputTypes.length == 0) {
throw new IllegalArgumentException
("inputTypes.length == 0!");
}
this.inputTypes = (inputTypes == STANDARD_INPUT_TYPE) ?
new Class<?>[] { ImageInputStream.class } :
inputTypes.clone();
// If length == 0, leave it null
if (writerSpiNames != null && writerSpiNames.length > 0) {
this.writerSpiNames = (String[])writerSpiNames.clone();
}
}
/** {@collect.stats}
* Returns an array of <code>Class</code> objects indicating what
* types of objects may be used as arguments to the reader's
* <code>setInput</code> method.
*
* <p> For most readers, which only accept input from an
* <code>ImageInputStream</code>, a single-element array
* containing <code>ImageInputStream.class</code> should be
* returned.
*
* @return a non-<code>null</code> array of
* <code>Class</code>objects of length at least 1.
*/
public Class[] getInputTypes() {
return (Class[])inputTypes.clone();
}
/** {@collect.stats}
* Returns <code>true</code> if the supplied source object appears
* to be of the format supported by this reader. Returning
* <code>true</code> from this method does not guarantee that
* reading will succeed, only that there appears to be a
* reasonable chance of success based on a brief inspection of the
* stream contents. If the source is an
* <code>ImageInputStream</code>, implementations will commonly
* check the first several bytes of the stream for a "magic
* number" associated with the format. Once actual reading has
* commenced, the reader may still indicate failure at any time
* prior to the completion of decoding.
*
* <p> It is important that the state of the object not be
* disturbed in order that other <code>ImageReaderSpi</code>s can
* properly determine whether they are able to decode the object.
* In particular, if the source is an
* <code>ImageInputStream</code>, a
* <code>mark</code>/<code>reset</code> pair should be used to
* preserve the stream position.
*
* <p> Formats such as "raw," which can potentially attempt
* to read nearly any stream, should return <code>false</code>
* in order to avoid being invoked in preference to a closer
* match.
*
* <p> If <code>source</code> is not an instance of one of the
* classes returned by <code>getInputTypes</code>, the method
* should simply return <code>false</code>.
*
* @param source the object (typically an
* <code>ImageInputStream</code>) to be decoded.
*
* @return <code>true</code> if it is likely that this stream can
* be decoded.
*
* @exception IllegalArgumentException if <code>source</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs while reading the
* stream.
*/
public abstract boolean canDecodeInput(Object source) throws IOException;
/** {@collect.stats}
* Returns an instance of the <code>ImageReader</code>
* implementation associated with this service provider.
* The returned object will initially be in an initial state
* as if its <code>reset</code> method had been called.
*
* <p> The default implementation simply returns
* <code>createReaderInstance(null)</code>.
*
* @return an <code>ImageReader</code> instance.
*
* @exception IOException if an error occurs during loading,
* or initialization of the reader class, or during instantiation
* or initialization of the reader object.
*/
public ImageReader createReaderInstance() throws IOException {
return createReaderInstance(null);
}
/** {@collect.stats}
* Returns an instance of the <code>ImageReader</code>
* implementation associated with this service provider.
* The returned object will initially be in an initial state
* as if its <code>reset</code> method had been called.
*
* <p> An <code>Object</code> may be supplied to the plug-in at
* construction time. The nature of the object is entirely
* plug-in specific.
*
* <p> Typically, a plug-in will implement this method using code
* such as <code>return new MyImageReader(this)</code>.
*
* @param extension a plug-in specific extension object, which may
* be <code>null</code>.
*
* @return an <code>ImageReader</code> instance.
*
* @exception IOException if the attempt to instantiate
* the reader fails.
* @exception IllegalArgumentException if the
* <code>ImageReader</code>'s contructor throws an
* <code>IllegalArgumentException</code> to indicate that the
* extension object is unsuitable.
*/
public abstract ImageReader createReaderInstance(Object extension)
throws IOException;
/** {@collect.stats}
* Returns <code>true</code> if the <code>ImageReader</code> object
* passed in is an instance of the <code>ImageReader</code>
* associated with this service provider.
*
* <p> The default implementation compares the fully-qualified
* class name of the <code>reader</code> argument with the class
* name passed into the constructor. This method may be overridden
* if more sophisticated checking is required.
*
* @param reader an <code>ImageReader</code> instance.
*
* @return <code>true</code> if <code>reader</code> is recognized.
*
* @exception IllegalArgumentException if <code>reader</code> is
* <code>null</code>.
*/
public boolean isOwnReader(ImageReader reader) {
if (reader == null) {
throw new IllegalArgumentException("reader == null!");
}
String name = reader.getClass().getName();
return name.equals(pluginClassName);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the fully
* qualified names of all the <code>ImageWriterSpi</code> classes
* that can understand the internal metadata representation used
* by the <code>ImageReader</code> associated with this service
* provider, or <code>null</code> if there are no such
* <code>ImageWriter</code>s specified. If a
* non-<code>null</code> value is returned, it must have non-zero
* length.
*
* <p> The first item in the array must be the name of the service
* provider for the "preferred" writer, as it will be used to
* instantiate the <code>ImageWriter</code> returned by
* <code>ImageIO.getImageWriter(ImageReader)</code>.
*
* <p> This mechanism may be used to obtain
* <code>ImageWriters</code> that will understand the internal
* structure of non-pixel meta-data (see
* <code>IIOTreeInfo</code>) generated by an
* <code>ImageReader</code>. By obtaining this data from the
* <code>ImageReader</code> and passing it on to one of the
* <code>ImageWriters</code> obtained with this method, a client
* program can read an image, modify it in some way, and write it
* back out while preserving all meta-data, without having to
* understand anything about the internal structure of the
* meta-data, or even about the image format.
*
* @return an array of <code>String</code>s of length at least 1
* containing names of <code>ImageWriterSpi</code>, or
* <code>null</code>.
*
* @see javax.imageio.ImageIO#getImageWriter(ImageReader)
*/
public String[] getImageWriterSpiNames() {
return writerSpiNames == null ?
null : (String[])writerSpiNames.clone();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormat;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.stream.ImageInputStream;
/** {@collect.stats}
* A superclass containing instance variables and methods common to
* <code>ImageReaderSpi</code> and <code>ImageWriterSpi</code>.
*
* @see IIORegistry
* @see ImageReaderSpi
* @see ImageWriterSpi
*
*/
public abstract class ImageReaderWriterSpi extends IIOServiceProvider {
/** {@collect.stats}
* An array of strings to be returned from
* <code>getFormatNames</code>, initially <code>null</code>.
* Constructors should set this to a non-<code>null</code> value.
*/
protected String[] names = null;
/** {@collect.stats}
* An array of strings to be returned from
* <code>getFileSuffixes</code>, initially <code>null</code>.
*/
protected String[] suffixes = null;
/** {@collect.stats}
* An array of strings to be returned from
* <code>getMIMETypes</code>, initially <code>null</code>.
*/
protected String[] MIMETypes = null;
/** {@collect.stats}
* A <code>String</code> containing the name of the associated
* plug-in class, initially <code>null</code>.
*/
protected String pluginClassName = null;
/** {@collect.stats}
* A boolean indicating whether this plug-in supports the
* standard metadata format for stream metadata, initially
* <code>false</code>.
*/
protected boolean supportsStandardStreamMetadataFormat = false;
/** {@collect.stats}
* A <code>String</code> containing the name of the native stream
* metadata format supported by this plug-in, initially
* <code>null</code>.
*/
protected String nativeStreamMetadataFormatName = null;
/** {@collect.stats}
* A <code>String</code> containing the class name of the native
* stream metadata format supported by this plug-in, initially
* <code>null</code>.
*/
protected String nativeStreamMetadataFormatClassName = null;
/** {@collect.stats}
* An array of <code>String</code>s containing the names of any
* additional stream metadata formats supported by this plug-in,
* initially <code>null</code>.
*/
protected String[] extraStreamMetadataFormatNames = null;
/** {@collect.stats}
* An array of <code>String</code>s containing the class names of
* any additional stream metadata formats supported by this plug-in,
* initially <code>null</code>.
*/
protected String[] extraStreamMetadataFormatClassNames = null;
/** {@collect.stats}
* A boolean indicating whether this plug-in supports the
* standard metadata format for image metadata, initially
* <code>false</code>.
*/
protected boolean supportsStandardImageMetadataFormat = false;
/** {@collect.stats}
* A <code>String</code> containing the name of the
* native stream metadata format supported by this plug-in,
* initially <code>null</code>.
*/
protected String nativeImageMetadataFormatName = null;
/** {@collect.stats}
* A <code>String</code> containing the class name of the
* native stream metadata format supported by this plug-in,
* initially <code>null</code>.
*/
protected String nativeImageMetadataFormatClassName = null;
/** {@collect.stats}
* An array of <code>String</code>s containing the names of any
* additional image metadata formats supported by this plug-in,
* initially <code>null</code>.
*/
protected String[] extraImageMetadataFormatNames = null;
/** {@collect.stats}
* An array of <code>String</code>s containing the class names of
* any additional image metadata formats supported by this
* plug-in, initially <code>null</code>.
*/
protected String[] extraImageMetadataFormatClassNames = null;
/** {@collect.stats}
* Constructs an <code>ImageReaderWriterSpi</code> with a given
* set of values.
*
* @param vendorName the vendor name, as a non-<code>null</code>
* <code>String</code>.
* @param version a version identifier, as a non-<code>null</code>
* <code>String</code>.
* @param names a non-<code>null</code> array of
* <code>String</code>s indicating the format names. At least one
* entry must be present.
* @param suffixes an array of <code>String</code>s indicating the
* common file suffixes. If no suffixes are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param MIMETypes an array of <code>String</code>s indicating
* the format's MIME types. If no MIME types are defined,
* <code>null</code> should be supplied. An array of length 0
* will be normalized to <code>null</code>.
* @param pluginClassName the fully-qualified name of the
* associated <code>ImageReader</code> or <code>ImageWriter</code>
* class, as a non-<code>null</code> <code>String</code>.
* @param supportsStandardStreamMetadataFormat a
* <code>boolean</code> that indicates whether a stream metadata
* object can use trees described by the standard metadata format.
* @param nativeStreamMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeStreamMetadataFormatName</code>.
* @param nativeStreamMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeStreamMetadataFormat</code>.
* @param extraStreamMetadataFormatNames an array of
* <code>String</code>s, or <code>null</code>, to be returned from
* <code>getExtraStreamMetadataFormatNames</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param extraStreamMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getStreamMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
* @param supportsStandardImageMetadataFormat a
* <code>boolean</code> that indicates whether an image metadata
* object can use trees described by the standard metadata format.
* @param nativeImageMetadataFormatName a
* <code>String</code>, or <code>null</code>, to be returned from
* <code>getNativeImageMetadataFormatName</code>.
* @param nativeImageMetadataFormatClassName a
* <code>String</code>, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getNativeImageMetadataFormat</code>.
* @param extraImageMetadataFormatNames an array of
* <code>String</code>s to be returned from
* <code>getExtraImageMetadataFormatNames</code>. An array of length 0
* is normalized to <code>null</code>.
* @param extraImageMetadataFormatClassNames an array of
* <code>String</code>s, or <code>null</code>, to be used to instantiate
* a metadata format object to be returned from
* <code>getImageMetadataFormat</code>. An array of length
* 0 is normalized to <code>null</code>.
*
* @exception IllegalArgumentException if <code>vendorName</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>version</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>names</code>
* is <code>null</code> or has length 0.
* @exception IllegalArgumentException if <code>pluginClassName</code>
* is <code>null</code>.
*/
public ImageReaderWriterSpi(String vendorName,
String version,
String[] names,
String[] suffixes,
String[] MIMETypes,
String pluginClassName,
boolean supportsStandardStreamMetadataFormat,
String nativeStreamMetadataFormatName,
String nativeStreamMetadataFormatClassName,
String[] extraStreamMetadataFormatNames,
String[] extraStreamMetadataFormatClassNames,
boolean supportsStandardImageMetadataFormat,
String nativeImageMetadataFormatName,
String nativeImageMetadataFormatClassName,
String[] extraImageMetadataFormatNames,
String[] extraImageMetadataFormatClassNames) {
super(vendorName, version);
if (names == null) {
throw new IllegalArgumentException("names == null!");
}
if (names.length == 0) {
throw new IllegalArgumentException("names.length == 0!");
}
if (pluginClassName == null) {
throw new IllegalArgumentException("pluginClassName == null!");
}
this.names = (String[])names.clone();
// If length == 0, leave it null
if (suffixes != null && suffixes.length > 0) {
this.suffixes = (String[])suffixes.clone();
}
// If length == 0, leave it null
if (MIMETypes != null && MIMETypes.length > 0) {
this.MIMETypes = (String[])MIMETypes.clone();
}
this.pluginClassName = pluginClassName;
this.supportsStandardStreamMetadataFormat =
supportsStandardStreamMetadataFormat;
this.nativeStreamMetadataFormatName = nativeStreamMetadataFormatName;
this.nativeStreamMetadataFormatClassName =
nativeStreamMetadataFormatClassName;
// If length == 0, leave it null
if (extraStreamMetadataFormatNames != null &&
extraStreamMetadataFormatNames.length > 0) {
this.extraStreamMetadataFormatNames =
(String[])extraStreamMetadataFormatNames.clone();
}
// If length == 0, leave it null
if (extraStreamMetadataFormatClassNames != null &&
extraStreamMetadataFormatClassNames.length > 0) {
this.extraStreamMetadataFormatClassNames =
(String[])extraStreamMetadataFormatClassNames.clone();
}
this.supportsStandardImageMetadataFormat =
supportsStandardImageMetadataFormat;
this.nativeImageMetadataFormatName = nativeImageMetadataFormatName;
this.nativeImageMetadataFormatClassName =
nativeImageMetadataFormatClassName;
// If length == 0, leave it null
if (extraImageMetadataFormatNames != null &&
extraImageMetadataFormatNames.length > 0) {
this.extraImageMetadataFormatNames =
(String[])extraImageMetadataFormatNames.clone();
}
// If length == 0, leave it null
if (extraImageMetadataFormatClassNames != null &&
extraImageMetadataFormatClassNames.length > 0) {
this.extraImageMetadataFormatClassNames =
(String[])extraImageMetadataFormatClassNames.clone();
}
}
/** {@collect.stats}
* Constructs a blank <code>ImageReaderWriterSpi</code>. It is up
* to the subclass to initialize instance variables and/or
* override method implementations in order to provide working
* versions of all methods.
*/
public ImageReaderWriterSpi() {
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing
* human-readable names for the formats that are generally usable
* by the <code>ImageReader</code> or <code>ImageWriter</code>
* implementation associated with this service provider. For
* example, a single <code>ImageReader</code> might be able to
* process both PBM and PNM files.
*
* @return a non-<code>null</code> array of <code>String</code>s
* or length at least 1 containing informal format names
* associated with this reader or writer.
*/
public String[] getFormatNames() {
return (String[])names.clone();
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing a list of
* file suffixes associated with the formats that are generally
* usable by the <code>ImageReader</code> or
* <code>ImageWriter</code> implementation associated with this
* service provider. For example, a single
* <code>ImageReader</code> might be able to process files with
* '.pbm' and '.pnm' suffixes, or both '.jpg' and '.jpeg'
* suffixes. If there are no known file suffixes,
* <code>null</code> will be returned.
*
* <p> Returning a particular suffix does not guarantee that files
* with that suffix can be processed; it merely indicates that it
* may be worthwhile attempting to decode or encode such files
* using this service provider.
*
* @return an array of <code>String</code>s or length at least 1
* containing common file suffixes associated with this reader or
* writer, or <code>null</code>.
*/
public String[] getFileSuffixes() {
return suffixes == null ? null : (String[])suffixes.clone();
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing a list of
* MIME types associated with the formats that are generally
* usable by the <code>ImageReader</code> or
* <code>ImageWriter</code> implementation associated with this
* service provider.
*
* <p> Ideally, only a single MIME type would be required in order
* to describe a particular format. However, for several reasons
* it is necessary to associate a list of types with each service
* provider. First, many common image file formats do not have
* standard MIME types, so a list of commonly used unofficial
* names will be required, such as <code>image/x-pbm</code> and
* <code>image/x-portable-bitmap</code>. Some file formats have
* official MIME types but may sometimes be referred to using
* their previous unofficial designations, such as
* <code>image/x-png</code> instead of the official
* <code>image/png</code>. Finally, a single service provider may
* be capable of parsing multiple distinct types from the MIME
* point of view, for example <code>image/x-xbitmap</code> and
* <code>image/x-xpixmap</code>.
*
* <p> Returning a particular MIME type does not guarantee that
* files claiming to be of that type can be processed; it merely
* indicates that it may be worthwhile attempting to decode or
* encode such files using this service provider.
*
* @return an array of <code>String</code>s or length at least 1
* containing MIME types associated with this reader or writer, or
* <code>null</code>.
*/
public String[] getMIMETypes() {
return MIMETypes == null ? null : (String[])MIMETypes.clone();
}
/** {@collect.stats}
* Returns the fully-qualified class name of the
* <code>ImageReader</code> or <code>ImageWriter</code> plug-in
* associated with this service provider.
*
* @return the class name, as a non-<code>null</code>
* <code>String</code>.
*/
public String getPluginClassName() {
return pluginClassName;
}
/** {@collect.stats}
* Returns <code>true</code> if the standard metadata format is
* among the document formats recognized by the
* <code>getAsTree</code> and <code>setFromTree</code> methods on
* the stream metadata objects produced or consumed by this
* plug-in.
*
* @return <code>true</code> if the standard format is supported
* for stream metadata.
*/
public boolean isStandardStreamMetadataFormatSupported() {
return supportsStandardStreamMetadataFormat;
}
/** {@collect.stats}
* Returns the name of the "native" stream metadata format for
* this plug-in, which typically allows for lossless encoding and
* transmission of the stream metadata stored in the format handled by
* this plug-in. If no such format is supported,
* <code>null</code>will be returned.
*
* <p> The default implementation returns the
* <code>nativeStreamMetadataFormatName</code> instance variable,
* which is typically set by the constructor.
*
* @return the name of the native stream metadata format, or
* <code>null</code>.
*
*/
public String getNativeStreamMetadataFormatName() {
return nativeStreamMetadataFormatName;
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the names
* of additional document formats, other than the native and
* standard formats, recognized by the
* <code>getAsTree</code> and <code>setFromTree</code> methods on
* the stream metadata objects produced or consumed by this
* plug-in.
*
* <p> If the plug-in does not handle metadata, null should be
* returned.
*
* <p> The set of formats may differ according to the particular
* images being read or written; this method should indicate all
* the additional formats supported by the plug-in under any
* circumstances.
*
* <p> The default implementation returns a clone of the
* <code>extraStreamMetadataFormatNames</code> instance variable,
* which is typically set by the constructor.
*
* @return an array of <code>String</code>s, or null.
*
* @see IIOMetadata#getMetadataFormatNames
* @see #getExtraImageMetadataFormatNames
* @see #getNativeStreamMetadataFormatName
*/
public String[] getExtraStreamMetadataFormatNames() {
return extraStreamMetadataFormatNames == null ?
null : (String[])extraStreamMetadataFormatNames.clone();
}
/** {@collect.stats}
* Returns <code>true</code> if the standard metadata format is
* among the document formats recognized by the
* <code>getAsTree</code> and <code>setFromTree</code> methods on
* the image metadata objects produced or consumed by this
* plug-in.
*
* @return <code>true</code> if the standard format is supported
* for image metadata.
*/
public boolean isStandardImageMetadataFormatSupported() {
return supportsStandardImageMetadataFormat;
}
/** {@collect.stats}
* Returns the name of the "native" image metadata format for
* this plug-in, which typically allows for lossless encoding and
* transmission of the image metadata stored in the format handled by
* this plug-in. If no such format is supported,
* <code>null</code>will be returned.
*
* <p> The default implementation returns the
* <code>nativeImageMetadataFormatName</code> instance variable,
* which is typically set by the constructor.
*
* @return the name of the native image metadata format, or
* <code>null</code>.
*
* @see #getExtraImageMetadataFormatNames
*/
public String getNativeImageMetadataFormatName() {
return nativeImageMetadataFormatName;
}
/** {@collect.stats}
* Returns an array of <code>String</code>s containing the names
* of additional document formats, other than the native and
* standard formats, recognized by the
* <code>getAsTree</code> and <code>setFromTree</code> methods on
* the image metadata objects produced or consumed by this
* plug-in.
*
* <p> If the plug-in does not handle image metadata, null should
* be returned.
*
* <p> The set of formats may differ according to the particular
* images being read or written; this method should indicate all
* the additional formats supported by the plug-in under any circumstances.
*
* <p> The default implementation returns a clone of the
* <code>extraImageMetadataFormatNames</code> instance variable,
* which is typically set by the constructor.
*
* @return an array of <code>String</code>s, or null.
*
* @see IIOMetadata#getMetadataFormatNames
* @see #getExtraStreamMetadataFormatNames
* @see #getNativeImageMetadataFormatName
*/
public String[] getExtraImageMetadataFormatNames() {
return extraImageMetadataFormatNames == null ?
null : (String[])extraImageMetadataFormatNames.clone();
}
/** {@collect.stats}
* Returns an <code>IIOMetadataFormat</code> object describing the
* given stream metadata format, or <code>null</code> if no
* description is available. The supplied name must be the native
* stream metadata format name, the standard metadata format name,
* or one of those returned by
* <code>getExtraStreamMetadataFormatNames</code>.
*
* @param formatName the desired stream metadata format.
*
* @return an <code>IIOMetadataFormat</code> object.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not a supported name.
*/
public IIOMetadataFormat getStreamMetadataFormat(String formatName) {
return getMetadataFormat(formatName,
supportsStandardStreamMetadataFormat,
nativeStreamMetadataFormatName,
nativeStreamMetadataFormatClassName,
extraStreamMetadataFormatNames,
extraStreamMetadataFormatClassNames);
}
/** {@collect.stats}
* Returns an <code>IIOMetadataFormat</code> object describing the
* given image metadata format, or <code>null</code> if no
* description is available. The supplied name must be the native
* iamge metadata format name, the standard metadata format name,
* or one of those returned by
* <code>getExtraImageMetadataFormatNames</code>.
*
* @param formatName the desired image metadata format.
*
* @return an <code>IIOMetadataFormat</code> object.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code> or is not a supported name.
*/
public IIOMetadataFormat getImageMetadataFormat(String formatName) {
return getMetadataFormat(formatName,
supportsStandardImageMetadataFormat,
nativeImageMetadataFormatName,
nativeImageMetadataFormatClassName,
extraImageMetadataFormatNames,
extraImageMetadataFormatClassNames);
}
private IIOMetadataFormat getMetadataFormat(String formatName,
boolean supportsStandard,
String nativeName,
String nativeClassName,
String [] extraNames,
String [] extraClassNames) {
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
if (supportsStandard && formatName.equals
(IIOMetadataFormatImpl.standardMetadataFormatName)) {
return IIOMetadataFormatImpl.getStandardFormatInstance();
}
String formatClassName = null;
if (formatName.equals(nativeName)) {
formatClassName = nativeClassName;
} else if (extraNames != null) {
for (int i = 0; i < extraNames.length; i++) {
if (formatName.equals(extraNames[i])) {
formatClassName = extraClassNames[i];
break; // out of for
}
}
}
if (formatClassName == null) {
throw new IllegalArgumentException("Unsupported format name");
}
try {
Class cls = Class.forName(formatClassName, true,
ClassLoader.getSystemClassLoader());
Method meth = cls.getMethod("getInstance");
return (IIOMetadataFormat) meth.invoke(null);
} catch (Exception e) {
RuntimeException ex =
new IllegalStateException ("Can't obtain format");
ex.initCause(e);
throw ex;
}
}
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.spi;
import javax.imageio.ImageTranscoder;
/** {@collect.stats}
* The service provider interface (SPI) for <code>ImageTranscoder</code>s.
* For more information on service provider classes, see the class comment
* for the <code>IIORegistry</code> class.
*
* @see IIORegistry
* @see javax.imageio.ImageTranscoder
*
*/
public abstract class ImageTranscoderSpi extends IIOServiceProvider {
/** {@collect.stats}
* Constructs a blank <code>ImageTranscoderSpi</code>. It is up
* to the subclass to initialize instance variables and/or
* override method implementations in order to provide working
* versions of all methods.
*/
protected ImageTranscoderSpi() {
}
/** {@collect.stats}
* Constructs an <code>ImageTranscoderSpi</code> with a given set
* of values.
*
* @param vendorName the vendor name.
* @param version a version identifier.
*/
public ImageTranscoderSpi(String vendorName,
String version) {
super(vendorName, version);
}
/** {@collect.stats}
* Returns the fully qualified class name of an
* <code>ImageReaderSpi</code> class that generates
* <code>IIOMetadata</code> objects that may be used as input to
* this transcoder.
*
* @return a <code>String</code> containing the fully-qualified
* class name of the <code>ImageReaderSpi</code> implementation class.
*
* @see ImageReaderSpi
*/
public abstract String getReaderServiceProviderName();
/** {@collect.stats}
* Returns the fully qualified class name of an
* <code>ImageWriterSpi</code> class that generates
* <code>IIOMetadata</code> objects that may be used as input to
* this transcoder.
*
* @return a <code>String</code> containing the fully-qualified
* class name of the <code>ImageWriterSpi</code> implementation class.
*
* @see ImageWriterSpi
*/
public abstract String getWriterServiceProviderName();
/** {@collect.stats}
* Returns an instance of the <code>ImageTranscoder</code>
* implementation associated with this service provider.
*
* @return an <code>ImageTranscoder</code> instance.
*/
public abstract ImageTranscoder createTranscoderInstance();
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
/** {@collect.stats}
* An interface to be implemented by objects that can determine the
* settings of an <code>IIOParam</code> object, either by putting up a
* GUI to obtain values from a user, or by other means. This
* interface merely specifies a generic <code>activate</code> method
* that invokes the controller, without regard for how the controller
* obtains values (<i>i.e.</i>, whether the controller puts up a GUI
* or merely computes a set of values is irrelevant to this
* interface).
*
* <p> Within the <code>activate</code> method, a controller obtains
* initial values by querying the <code>IIOParam</code> object's
* <code>get</code> methods, modifies values by whatever means, then
* invokes the <code>IIOParam</code> object's <code>set</code> methods
* to modify the appropriate settings. Normally, these
* <code>set</code> methods will be invoked all at once at a final
* commit in order that a cancel operation not disturb existing
* values. In general, applications may expect that when the
* <code>activate</code> method returns <code>true</code>, the
* <code>IIOParam</code> object is ready for use in a read or write
* operation.
*
* <p> Vendors may choose to provide GUIs for the
* <code>IIOParam</code> subclasses they define for a particular
* plug-in. These can be set up as default controllers in the
* corresponding <code>IIOParam</code> subclasses.
*
* <p> Applications may override any default GUIs and provide their
* own controllers embedded in their own framework. All that is
* required is that the<code>activate</code> method behave modally
* (not returning until either cancelled or committed), though it need
* not put up an explicitly modal dialog. Such a non-modal GUI
* component would be coded roughly as follows:
*
* <br>
* <pre>
* class MyGUI extends SomeComponent implements IIOParamController {
*
* public MyGUI() {
* // ...
* setEnabled(false);
* }
*
* public boolean activate(IIOParam param) {
* // disable other components if desired
* setEnabled(true);
* // go to sleep until either cancelled or committed
* boolean ret = false;
* if (!cancelled) {
* // set values on param
* ret = true;
* }
* setEnabled(false);
* // enable any components disabled above
* return ret;
* }
* </pre>
*
* <p> Alternatively, an algorithmic process such as a database lookup
* or the parsing of a command line could be used as a controller, in
* which case the <code>activate</code> method would simply look up or
* compute the settings, call the <code>IIOParam.setXXX</code>
* methods, and return <code>true</code>.
*
* @see IIOParam#setController
* @see IIOParam#getController
* @see IIOParam#getDefaultController
* @see IIOParam#hasController
* @see IIOParam#activateController
*
*/
public interface IIOParamController {
/** {@collect.stats}
* Activates the controller. If <code>true</code> is returned,
* all settings in the <code>IIOParam</code> object should be
* ready for use in a read or write operation. If
* <code>false</code> is returned, no settings in the
* <code>IIOParam</code> object will be disturbed (<i>i.e.</i>,
* the user canceled the operation).
*
* @param param the <code>IIOParam</code> object to be modified.
*
* @return <code>true</code> if the <code>IIOParam</code> has been
* modified, <code>false</code> otherwise.
*
* @exception IllegalArgumentException if <code>param</code> is
* <code>null</code> or is not an instance of the correct class.
*/
boolean activate(IIOParam param);
}
|
Java
|
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
/** {@collect.stats}
* A class representing a mutable reference to an array of bytes and
* an offset and length within that array. <code>IIOByteBuffer</code>
* is used by <code>ImageInputStream</code> to supply a sequence of bytes
* to the caller, possibly with fewer copies than using the conventional
* <code>read</code> methods that take a user-supplied byte array.
*
* <p> The byte array referenced by an <code>IIOByteBuffer</code> will
* generally be part of an internal data structure belonging to an
* <code>ImageReader</code> implementation; its contents should be
* considered read-only and must not be modified.
*
*/
public class IIOByteBuffer {
private byte[] data;
private int offset;
private int length;
/** {@collect.stats}
* Constructs an <code>IIOByteBuffer</code> that references a
* given byte array, offset, and length.
*
* @param data a byte array.
* @param offset an int offset within the array.
* @param length an int specifying the length of the data of
* interest within byte array, in bytes.
*/
public IIOByteBuffer(byte[] data, int offset, int length) {
this.data = data;
this.offset = offset;
this.length = length;
}
/** {@collect.stats}
* Returns a reference to the byte array. The returned value should
* be treated as read-only, and only the portion specified by the
* values of <code>getOffset</code> and <code>getLength</code> should
* be used.
*
* @return a byte array reference.
*
* @see #getOffset
* @see #getLength
* @see #setData
*/
public byte[] getData() {
return data;
}
/** {@collect.stats}
* Updates the array reference that will be returned by subsequent calls
* to the <code>getData</code> method.
*
* @param data a byte array reference containing the new data value.
*
* @see #getData
*/
public void setData(byte[] data) {
this.data = data;
}
/** {@collect.stats}
* Returns the offset within the byte array returned by
* <code>getData</code> at which the data of interest start.
*
* @return an int offset.
*
* @see #getData
* @see #getLength
* @see #setOffset
*/
public int getOffset() {
return offset;
}
/** {@collect.stats}
* Updates the value that will be returned by subsequent calls
* to the <code>getOffset</code> method.
*
* @param offset an int containing the new offset value.
*
* @see #getOffset
*/
public void setOffset(int offset) {
this.offset = offset;
}
/** {@collect.stats}
* Returns the length of the data of interest within the byte
* array returned by <code>getData</code>.
*
* @return an int length.
*
* @see #getData
* @see #getOffset
* @see #setLength
*/
public int getLength() {
return length;
}
/** {@collect.stats}
* Updates the value that will be returned by subsequent calls
* to the <code>getLength</code> method.
*
* @param length an int containing the new length value.
*
* @see #getLength
*/
public void setLength(int length) {
this.length = length;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.InputStream;
import java.io.IOException;
import com.sun.imageio.stream.StreamFinalizer;
import sun.java2d.Disposer;
import sun.java2d.DisposerRecord;
/** {@collect.stats}
* An implementation of <code>ImageInputStream</code> that gets its
* input from a regular <code>InputStream</code>. A memory buffer is
* used to cache at least the data between the discard position and
* the current read position.
*
* <p> In general, it is preferable to use a
* <code>FileCacheImageInputStream</code> when reading from a regular
* <code>InputStream</code>. This class is provided for cases where
* it is not possible to create a writable temporary file.
*
*/
public class MemoryCacheImageInputStream extends ImageInputStreamImpl {
private InputStream stream;
private MemoryCache cache = new MemoryCache();
/** {@collect.stats} The referent to be registered with the Disposer. */
private final Object disposerReferent;
/** {@collect.stats} The DisposerRecord that resets the underlying MemoryCache. */
private final DisposerRecord disposerRecord;
/** {@collect.stats}
* Constructs a <code>MemoryCacheImageInputStream</code> that will read
* from a given <code>InputStream</code>.
*
* @param stream an <code>InputStream</code> to read from.
*
* @exception IllegalArgumentException if <code>stream</code> is
* <code>null</code>.
*/
public MemoryCacheImageInputStream(InputStream stream) {
if (stream == null) {
throw new IllegalArgumentException("stream == null!");
}
this.stream = stream;
disposerRecord = new StreamDisposerRecord(cache);
if (getClass() == MemoryCacheImageInputStream.class) {
disposerReferent = new Object();
Disposer.addRecord(disposerReferent, disposerRecord);
} else {
disposerReferent = new StreamFinalizer(this);
}
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
long pos = cache.loadFromStream(stream, streamPos+1);
if (pos >= streamPos+1) {
return cache.read(streamPos++);
} else {
return -1;
}
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
if (b == null) {
throw new NullPointerException("b == null!");
}
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off+len > b.length || off+len < 0!");
}
bitOffset = 0;
if (len == 0) {
return 0;
}
long pos = cache.loadFromStream(stream, streamPos+len);
len = (int)(pos - streamPos); // In case stream ended early
if (len > 0) {
cache.read(b, off, len, streamPos);
streamPos += len;
return len;
} else {
return -1;
}
}
public void flushBefore(long pos) throws IOException {
super.flushBefore(pos); // this will call checkClosed() for us
cache.disposeBefore(pos);
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageInputStream</code> caches data in order to allow
* seeking backwards.
*
* @return <code>true</code>.
*
* @see #isCachedMemory
* @see #isCachedFile
*/
public boolean isCached() {
return true;
}
/** {@collect.stats}
* Returns <code>false</code> since this
* <code>ImageInputStream</code> does not maintain a file cache.
*
* @return <code>false</code>.
*
* @see #isCached
* @see #isCachedMemory
*/
public boolean isCachedFile() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageInputStream</code> maintains a main memory cache.
*
* @return <code>true</code>.
*
* @see #isCached
* @see #isCachedFile
*/
public boolean isCachedMemory() {
return true;
}
/** {@collect.stats}
* Closes this <code>MemoryCacheImageInputStream</code>, freeing
* the cache. The source <code>InputStream</code> is not closed.
*/
public void close() throws IOException {
super.close();
disposerRecord.dispose(); // this resets the MemoryCache
stream = null;
cache = null;
}
/** {@collect.stats}
* {@inheritDoc}
*/
protected void finalize() throws Throwable {
// Empty finalizer: for performance reasons we instead use the
// Disposer mechanism for ensuring that the underlying
// MemoryCache is reset prior to garbage collection
}
private static class StreamDisposerRecord implements DisposerRecord {
private MemoryCache cache;
public StreamDisposerRecord(MemoryCache cache) {
this.cache = cache;
}
public synchronized void dispose() {
if (cache != null) {
cache.reset();
cache = null;
}
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.DataOutput;
import java.io.IOException;
/** {@collect.stats}
* A seekable output stream interface for use by
* <code>ImageWriter</code>s. Various output destinations, such as
* <code>OutputStream</code>s and <code>File</code>s, as well as
* future fast I/O destinations may be "wrapped" by a suitable
* implementation of this interface for use by the Image I/O API.
*
* <p> Unlike a standard <code>OutputStream</code>, ImageOutputStream
* extends its counterpart, <code>ImageInputStream</code>. Thus it is
* possible to read from the stream as it is being written. The same
* seek and flush positions apply to both reading and writing, although
* the semantics for dealing with a non-zero bit offset before a byte-aligned
* write are necessarily different from the semantics for dealing with
* a non-zero bit offset before a byte-aligned read. When reading bytes,
* any bit offset is set to 0 before the read; when writing bytes, a
* non-zero bit offset causes the remaining bits in the byte to be written
* as 0s. The byte-aligned write then starts at the next byte position.
*
* @see ImageInputStream
*
*/
public interface ImageOutputStream extends ImageInputStream, DataOutput {
/** {@collect.stats}
* Writes a single byte to the stream at the current position.
* The 24 high-order bits of <code>b</code> are ignored.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write. Implementers can use the
* {@link ImageOutputStreamImpl#flushBits <code>flushBits</code>}
* method of {@link ImageOutputStreamImpl
* <code>ImageOutputStreamImpl</code>} to guarantee this.
*
* @param b an <code>int</code> whose lower 8 bits are to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/** {@collect.stats}
* Writes a sequence of bytes to the stream at the current
* position. If <code>b.length</code> is 0, nothing is written.
* The byte <code>b[0]</code> is written first, then the byte
* <code>b[1]</code>, and so on.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param b an array of <code>byte</code>s to be written.
*
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void write(byte b[]) throws IOException;
/** {@collect.stats}
* Writes a sequence of bytes to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The byte <code>b[off]</code> is written first, then the byte
* <code>b[off + 1]</code>, and so on.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write. Implementers can use the
* {@link ImageOutputStreamImpl#flushBits <code>flushBits</code>}
* method of {@link ImageOutputStreamImpl
* <code>ImageOutputStreamImpl</code>} to guarantee this.
*
* @param b an array of <code>byte</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>byte</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>b.length</code>.
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void write(byte b[], int off, int len) throws IOException;
/** {@collect.stats}
* Writes a <code>boolean</code> value to the stream. If
* <code>v</code> is true, the value <code>(byte)1</code> is
* written; if <code>v</code> is false, the value
* <code>(byte)0</code> is written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v the <code>boolean</code> to be written.
*
* @exception IOException if an I/O error occurs.
*/
void writeBoolean(boolean v) throws IOException;
/** {@collect.stats}
* Writes the 8 low-order bits of <code>v</code> to the
* stream. The 24 high-order bits of <code>v</code> are ignored.
* (This means that <code>writeByte</code> does exactly the same
* thing as <code>write</code> for an integer argument.)
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v an <code>int</code> containing the byte value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeByte(int v) throws IOException;
/** {@collect.stats}
* Writes the 16 low-order bits of <code>v</code> to the
* stream. The 16 high-order bits of <code>v</code> are ignored.
* If the stream uses network byte order, the bytes written, in
* order, will be:
*
* <pre>
* (byte)((v >> 8) & 0xff)
* (byte)(v & 0xff)
* </pre>
*
* Otherwise, the bytes written will be:
*
* <pre>
* (byte)(v & 0xff)
* (byte)((v >> 8) & 0xff)
* </pre>
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v an <code>int</code> containing the short value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeShort(int v) throws IOException;
/** {@collect.stats}
* This method is a synonym for
* {@link #writeShort <code>writeShort</code>}.
*
* @param v an <code>int</code> containing the char (unsigned
* short) value to be written.
*
* @exception IOException if an I/O error occurs.
*
* @see #writeShort(int)
*/
void writeChar(int v) throws IOException;
/** {@collect.stats}
* Writes the 32 bits of <code>v</code> to the stream. If the
* stream uses network byte order, the bytes written, in order,
* will be:
*
* <pre>
* (byte)((v >> 24) & 0xff)
* (byte)((v >> 16) & 0xff)
* (byte)((v >> 8) & 0xff)
* (byte)(v & 0xff)
* </pre>
*
* Otheriwse, the bytes written will be:
*
* <pre>
* (byte)(v & 0xff)
* (byte)((v >> 8) & 0xff)
* (byte)((v >> 16) & 0xff)
* (byte)((v >> 24) & 0xff)
* </pre>
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v an <code>int</code> containing the value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeInt(int v) throws IOException;
/** {@collect.stats}
* Writes the 64 bits of <code>v</code> to the stream. If the
* stream uses network byte order, the bytes written, in order,
* will be:
*
* <pre>
* (byte)((v >> 56) & 0xff)
* (byte)((v >> 48) & 0xff)
* (byte)((v >> 40) & 0xff)
* (byte)((v >> 32) & 0xff)
* (byte)((v >> 24) & 0xff)
* (byte)((v >> 16) & 0xff)
* (byte)((v >> 8) & 0xff)
* (byte)(v & 0xff)
* </pre>
*
* Otherwise, the bytes written will be:
*
* <pre>
* (byte)(v & 0xff)
* (byte)((v >> 8) & 0xff)
* (byte)((v >> 16) & 0xff)
* (byte)((v >> 24) & 0xff)
* (byte)((v >> 32) & 0xff)
* (byte)((v >> 40) & 0xff)
* (byte)((v >> 48) & 0xff)
* (byte)((v >> 56) & 0xff)
* </pre>
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v a <code>long</code> containing the value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeLong(long v) throws IOException;
/** {@collect.stats}
* Writes a <code>float</code> value, which is comprised of four
* bytes, to the output stream. It does this as if it first
* converts this <code>float</code> value to an <code>int</code>
* in exactly the manner of the <code>Float.floatToIntBits</code>
* method and then writes the int value in exactly the manner of
* the <code>writeInt</code> method.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v a <code>float</code> containing the value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeFloat(float v) throws IOException;
/** {@collect.stats}
* Writes a <code>double</code> value, which is comprised of four
* bytes, to the output stream. It does this as if it first
* converts this <code>double</code> value to an <code>long</code>
* in exactly the manner of the
* <code>Double.doubleToLongBits</code> method and then writes the
* long value in exactly the manner of the <code>writeLong</code>
* method.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param v a <code>double</code> containing the value to be
* written.
*
* @exception IOException if an I/O error occurs.
*/
void writeDouble(double v) throws IOException;
/** {@collect.stats}
* Writes a string to the output stream. For every character in
* the string <code>s</code>, taken in order, one byte is written
* to the output stream. If <code>s</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown.
*
* <p> If <code>s.length</code> is zero, then no bytes are
* written. Otherwise, the character <code>s[0]</code> is written
* first, then <code>s[1]</code>, and so on; the last character
* written is <code>s[s.length-1]</code>. For each character, one
* byte is written, the low-order byte, in exactly the manner of
* the <code>writeByte</code> method. The high-order eight bits of
* each character in the string are ignored.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param s a <code>String</code> containing the value to be
* written.
*
* @exception NullPointerException if <code>s</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeBytes(String s) throws IOException;
/** {@collect.stats}
* Writes a string to the output stream. For every character in
* the string <code>s</code>, taken in order, two bytes are
* written to the output stream, ordered according to the current
* byte order setting. If network byte order is being used, the
* high-order byte is written first; the order is reversed
* otherwise. If <code>s</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown.
*
* <p> If <code>s.length</code> is zero, then no bytes are
* written. Otherwise, the character <code>s[0]</code> is written
* first, then <code>s[1]</code>, and so on; the last character
* written is <code>s[s.length-1]</code>.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param s a <code>String</code> containing the value to be
* written.
*
* @exception NullPointerException if <code>s</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeChars(String s) throws IOException;
/** {@collect.stats}
* Writes two bytes of length information to the output stream in
* network byte order, followed by the
* <a href="../../../java/io/DataInput.html#modified-utf-8">modified
* UTF-8</a>
* representation of every character in the string <code>s</code>.
* If <code>s</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown. Each character in
* the string <code>s</code> is converted to a group of one, two,
* or three bytes, depending on the value of the character.
*
* <p> If a character <code>c</code> is in the range
* <code>\u0001</code> through <code>\u007f</code>, it is
* represented by one byte:
*
* <p><pre>
* (byte)c
* </pre>
*
* <p> If a character <code>c</code> is <code>\u0000</code> or
* is in the range <code>\u0080</code> through
* <code>\u07ff</code>, then it is represented by two bytes,
* to be written in the order shown:
*
* <p> <pre><code>
* (byte)(0xc0 | (0x1f & (c >> 6)))
* (byte)(0x80 | (0x3f & c))
* </code></pre>
*
* <p> If a character <code>c</code> is in the range
* <code>\u0800</code> through <code>uffff</code>, then it is
* represented by three bytes, to be written in the order shown:
*
* <p> <pre><code>
* (byte)(0xe0 | (0x0f & (c >> 12)))
* (byte)(0x80 | (0x3f & (c >> 6)))
* (byte)(0x80 | (0x3f & c))
* </code></pre>
*
* <p> First, the total number of bytes needed to represent all
* the characters of <code>s</code> is calculated. If this number
* is larger than <code>65535</code>, then a
* <code>UTFDataFormatException</code> is thrown. Otherwise, this
* length is written to the output stream in exactly the manner of
* the <code>writeShort</code> method; after this, the one-, two-,
* or three-byte representation of each character in the string
* <code>s</code> is written.
*
* <p> The current byte order setting is ignored.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* <p><strong>Note:</strong> This method should not be used in
* the implementation of image formats that use standard UTF-8,
* because the modified UTF-8 used here is incompatible with
* standard UTF-8.
*
* @param s a <code>String</code> containing the value to be
* written.
*
* @exception NullPointerException if <code>s</code> is
* <code>null</code>.
* @exception UTFDataFormatException if the modified UTF-8
* representation of <code>s</code> requires more than 65536 bytes.
* @exception IOException if an I/O error occurs.
*/
void writeUTF(String s) throws IOException;
/** {@collect.stats}
* Writes a sequence of shorts to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The short <code>s[off]</code> is written first, then the short
* <code>s[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param s an array of <code>short</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>short</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>s.length</code>.
* @exception NullPointerException if <code>s</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeShorts(short[] s, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a sequence of chars to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The char <code>c[off]</code> is written first, then the char
* <code>c[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param c an array of <code>char</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>char</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>c.length</code>.
* @exception NullPointerException if <code>c</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeChars(char[] c, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a sequence of ints to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The int <code>i[off]</code> is written first, then the int
* <code>i[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param i an array of <code>int</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>int</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>i.length</code>.
* @exception NullPointerException if <code>i</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeInts(int[] i, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a sequence of longs to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The long <code>l[off]</code> is written first, then the long
* <code>l[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param l an array of <code>long</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>long</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>l.length</code>.
* @exception NullPointerException if <code>l</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeLongs(long[] l, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a sequence of floats to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The float <code>f[off]</code> is written first, then the float
* <code>f[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param f an array of <code>float</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>float</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>f.length</code>.
* @exception NullPointerException if <code>f</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeFloats(float[] f, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a sequence of doubles to the stream at the current
* position. If <code>len</code> is 0, nothing is written.
* The double <code>d[off]</code> is written first, then the double
* <code>d[off + 1]</code>, and so on. The byte order of the
* stream is used to determine the order in which the individual
* bytes are written.
*
* <p> If the bit offset within the stream is non-zero, the
* remainder of the current byte is padded with 0s
* and written out first. The bit offset will be 0 after the
* write.
*
* @param d an array of <code>doubles</code>s to be written.
* @param off the start offset in the data.
* @param len the number of <code>double</code>s to write.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>d.length</code>.
* @exception NullPointerException if <code>d</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
void writeDoubles(double[] d, int off, int len) throws IOException;
/** {@collect.stats}
* Writes a single bit, given by the least significant bit of the
* argument, to the stream at the current bit offset within the
* current byte position. The upper 31 bits of the argument are
* ignored. The given bit replaces the previous bit at that
* position. The bit offset is advanced by one and reduced modulo
* 8.
*
* <p> If any bits of a particular byte have never been set
* at the time the byte is flushed to the destination, those
* bits will be set to 0 automatically.
*
* @param bit an <code>int</code> whose least significant bit
* is to be written to the stream.
*
* @exception IOException if an I/O error occurs.
*/
void writeBit(int bit) throws IOException;
/** {@collect.stats}
* Writes a sequence of bits, given by the <code>numBits</code>
* least significant bits of the <code>bits</code> argument in
* left-to-right order, to the stream at the current bit offset
* within the current byte position. The upper <code>64 -
* numBits</code> bits of the argument are ignored. The bit
* offset is advanced by <code>numBits</code> and reduced modulo
* 8. Note that a bit offset of 0 always indicates the
* most-significant bit of the byte, and bytes of bits are written
* out in sequence as they are encountered. Thus bit writes are
* always effectively in network byte order. The actual stream
* byte order setting is ignored.
*
* <p> Bit data may be accumulated in memory indefinitely, until
* <code>flushBefore</code> is called. At that time, all bit data
* prior to the flushed position will be written.
*
* <p> If any bits of a particular byte have never been set
* at the time the byte is flushed to the destination, those
* bits will be set to 0 automatically.
*
* @param bits a <code>long</code> containing the bits to be
* written, starting with the bit in position <code>numBits -
* 1</code> down to the least significant bit.
*
* @param numBits an <code>int</code> between 0 and 64, inclusive.
*
* @exception IllegalArgumentException if <code>numBits</code> is
* not between 0 and 64, inclusive.
* @exception IOException if an I/O error occurs.
*/
void writeBits(long bits, int numBits) throws IOException;
/** {@collect.stats}
* Flushes all data prior to the given position to the underlying
* destination, such as an <code>OutputStream</code> or
* <code>File</code>. Attempting to seek to the flushed portion
* of the stream will result in an
* <code>IndexOutOfBoundsException</code>.
*
* @param pos a <code>long</code> containing the length of the
* stream prefix that may be flushed to the destination.
*
* @exception IndexOutOfBoundsException if <code>pos</code> lies
* in the flushed portion of the stream or past the current stream
* position.
* @exception IOException if an I/O error occurs.
*/
void flushBefore(long pos) throws IOException;
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import com.sun.imageio.stream.StreamCloser;
/** {@collect.stats}
* An implementation of <code>ImageOutputStream</code> that writes its
* output to a regular <code>OutputStream</code>. A file is used to
* cache data until it is flushed to the output stream.
*
*/
public class FileCacheImageOutputStream extends ImageOutputStreamImpl {
private OutputStream stream;
private File cacheFile;
private RandomAccessFile cache;
// Pos after last (rightmost) byte written
private long maxStreamPos = 0L;
/** {@collect.stats} The CloseAction that closes the stream in
* the StreamCloser's shutdown hook */
private final StreamCloser.CloseAction closeAction;
/** {@collect.stats}
* Constructs a <code>FileCacheImageOutputStream</code> that will write
* to a given <code>outputStream</code>.
*
* <p> A temporary file is used as a cache. If
* <code>cacheDir</code>is non-<code>null</code> and is a
* directory, the file will be created there. If it is
* <code>null</code>, the system-dependent default temporary-file
* directory will be used (see the documentation for
* <code>File.createTempFile</code> for details).
*
* @param stream an <code>OutputStream</code> to write to.
* @param cacheDir a <code>File</code> indicating where the
* cache file should be created, or <code>null</code> to use the
* system directory.
*
* @exception IllegalArgumentException if <code>stream</code>
* is <code>null</code>.
* @exception IllegalArgumentException if <code>cacheDir</code> is
* non-<code>null</code> but is not a directory.
* @exception IOException if a cache file cannot be created.
*/
public FileCacheImageOutputStream(OutputStream stream, File cacheDir)
throws IOException {
if (stream == null) {
throw new IllegalArgumentException("stream == null!");
}
if ((cacheDir != null) && !(cacheDir.isDirectory())) {
throw new IllegalArgumentException("Not a directory!");
}
this.stream = stream;
this.cacheFile =
File.createTempFile("imageio", ".tmp", cacheDir);
this.cache = new RandomAccessFile(cacheFile, "rw");
this.closeAction = StreamCloser.createCloseAction(this);
StreamCloser.addToQueue(closeAction);
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
int val = cache.read();
if (val != -1) {
++streamPos;
}
return val;
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
if (b == null) {
throw new NullPointerException("b == null!");
}
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off+len > b.length || off+len < 0!");
}
bitOffset = 0;
if (len == 0) {
return 0;
}
int nbytes = cache.read(b, off, len);
if (nbytes != -1) {
streamPos += nbytes;
}
return nbytes;
}
public void write(int b) throws IOException {
flushBits(); // this will call checkClosed() for us
cache.write(b);
++streamPos;
maxStreamPos = Math.max(maxStreamPos, streamPos);
}
public void write(byte[] b, int off, int len) throws IOException {
flushBits(); // this will call checkClosed() for us
cache.write(b, off, len);
streamPos += len;
maxStreamPos = Math.max(maxStreamPos, streamPos);
}
public long length() {
try {
checkClosed();
return cache.length();
} catch (IOException e) {
return -1L;
}
}
/** {@collect.stats}
* Sets the current stream position and resets the bit offset to
* 0. It is legal to seek past the end of the file; an
* <code>EOFException</code> will be thrown only if a read is
* performed. The file length will not be increased until a write
* is performed.
*
* @exception IndexOutOfBoundsException if <code>pos</code> is smaller
* than the flushed position.
* @exception IOException if any other I/O error occurs.
*/
public void seek(long pos) throws IOException {
checkClosed();
if (pos < flushedPos) {
throw new IndexOutOfBoundsException();
}
cache.seek(pos);
this.streamPos = cache.getFilePointer();
maxStreamPos = Math.max(maxStreamPos, streamPos);
this.bitOffset = 0;
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageOutputStream</code> caches data in order to allow
* seeking backwards.
*
* @return <code>true</code>.
*
* @see #isCachedMemory
* @see #isCachedFile
*/
public boolean isCached() {
return true;
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageOutputStream</code> maintains a file cache.
*
* @return <code>true</code>.
*
* @see #isCached
* @see #isCachedMemory
*/
public boolean isCachedFile() {
return true;
}
/** {@collect.stats}
* Returns <code>false</code> since this
* <code>ImageOutputStream</code> does not maintain a main memory
* cache.
*
* @return <code>false</code>.
*
* @see #isCached
* @see #isCachedFile
*/
public boolean isCachedMemory() {
return false;
}
/** {@collect.stats}
* Closes this <code>FileCacheImageOututStream</code>. All
* pending data is flushed to the output, and the cache file
* is closed and removed. The destination <code>OutputStream</code>
* is not closed.
*
* @exception IOException if an error occurs.
*/
public void close() throws IOException {
maxStreamPos = cache.length();
seek(maxStreamPos);
flushBefore(maxStreamPos);
super.close();
cache.close();
cache = null;
cacheFile.delete();
cacheFile = null;
stream.flush();
stream = null;
StreamCloser.removeFromQueue(closeAction);
}
public void flushBefore(long pos) throws IOException {
long oFlushedPos = flushedPos;
super.flushBefore(pos); // this will call checkClosed() for us
long flushBytes = flushedPos - oFlushedPos;
if (flushBytes > 0) {
int bufLen = 512;
byte[] buf = new byte[bufLen];
cache.seek(oFlushedPos);
while (flushBytes > 0) {
int len = (int)Math.min(flushBytes, bufLen);
cache.readFully(buf, 0, len);
stream.write(buf, 0, len);
flushBytes -= len;
}
stream.flush();
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.sun.imageio.stream.CloseableDisposerRecord;
import com.sun.imageio.stream.StreamFinalizer;
import sun.java2d.Disposer;
/** {@collect.stats}
* An implementation of <code>ImageOutputStream</code> that writes its
* output directly to a <code>File</code> or
* <code>RandomAccessFile</code>.
*
*/
public class FileImageOutputStream extends ImageOutputStreamImpl {
private RandomAccessFile raf;
/** {@collect.stats} The referent to be registered with the Disposer. */
private final Object disposerReferent;
/** {@collect.stats} The DisposerRecord that closes the underlying RandomAccessFile. */
private final CloseableDisposerRecord disposerRecord;
/** {@collect.stats}
* Constructs a <code>FileImageOutputStream</code> that will write
* to a given <code>File</code>.
*
* @param f a <code>File</code> to write to.
*
* @exception IllegalArgumentException if <code>f</code> is
* <code>null</code>.
* @exception SecurityException if a security manager exists
* and does not allow write access to the file.
* @exception FileNotFoundException if <code>f</code> does not denote
* a regular file or it cannot be opened for reading and writing for any
* other reason.
* @exception IOException if an I/O error occurs.
*/
public FileImageOutputStream(File f)
throws FileNotFoundException, IOException {
this(f == null ? null : new RandomAccessFile(f, "rw"));
}
/** {@collect.stats}
* Constructs a <code>FileImageOutputStream</code> that will write
* to a given <code>RandomAccessFile</code>.
*
* @param raf a <code>RandomAccessFile</code> to write to.
*
* @exception IllegalArgumentException if <code>raf</code> is
* <code>null</code>.
*/
public FileImageOutputStream(RandomAccessFile raf) {
if (raf == null) {
throw new IllegalArgumentException("raf == null!");
}
this.raf = raf;
disposerRecord = new CloseableDisposerRecord(raf);
if (getClass() == FileImageOutputStream.class) {
disposerReferent = new Object();
Disposer.addRecord(disposerReferent, disposerRecord);
} else {
disposerReferent = new StreamFinalizer(this);
}
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
int val = raf.read();
if (val != -1) {
++streamPos;
}
return val;
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
bitOffset = 0;
int nbytes = raf.read(b, off, len);
if (nbytes != -1) {
streamPos += nbytes;
}
return nbytes;
}
public void write(int b) throws IOException {
flushBits(); // this will call checkClosed() for us
raf.write(b);
++streamPos;
}
public void write(byte[] b, int off, int len) throws IOException {
flushBits(); // this will call checkClosed() for us
raf.write(b, off, len);
streamPos += len;
}
public long length() {
try {
checkClosed();
return raf.length();
} catch (IOException e) {
return -1L;
}
}
/** {@collect.stats}
* Sets the current stream position and resets the bit offset to
* 0. It is legal to seeking past the end of the file; an
* <code>EOFException</code> will be thrown only if a read is
* performed. The file length will not be increased until a write
* is performed.
*
* @exception IndexOutOfBoundsException if <code>pos</code> is smaller
* than the flushed position.
* @exception IOException if any other I/O error occurs.
*/
public void seek(long pos) throws IOException {
checkClosed();
if (pos < flushedPos) {
throw new IndexOutOfBoundsException("pos < flushedPos!");
}
bitOffset = 0;
raf.seek(pos);
streamPos = raf.getFilePointer();
}
public void close() throws IOException {
super.close();
disposerRecord.dispose(); // this closes the RandomAccessFile
raf = null;
}
/** {@collect.stats}
* {@inheritDoc}
*/
protected void finalize() throws Throwable {
// Empty finalizer: for performance reasons we instead use the
// Disposer mechanism for ensuring that the underlying
// RandomAccessFile is closed prior to garbage collection
}
}
|
Java
|
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteOrder;
/** {@collect.stats}
* A seekable input stream interface for use by
* <code>ImageReader</code>s. Various input sources, such as
* <code>InputStream</code>s and <code>File</code>s,
* as well as future fast I/O sources may be "wrapped" by a suitable
* implementation of this interface for use by the Image I/O API.
*
* @see ImageInputStreamImpl
* @see FileImageInputStream
* @see FileCacheImageInputStream
* @see MemoryCacheImageInputStream
*
*/
public interface ImageInputStream extends DataInput {
/** {@collect.stats}
* Sets the desired byte order for future reads of data values
* from this stream. For example, the sequence of bytes '0x01
* 0x02 0x03 0x04' if read as a 4-byte integer would have the
* value '0x01020304' using network byte order and the value
* '0x04030201' under the reverse byte order.
*
* <p> The enumeration class <code>java.nio.ByteOrder</code> is
* used to specify the byte order. A value of
* <code>ByteOrder.BIG_ENDIAN</code> specifies so-called
* big-endian or network byte order, in which the high-order byte
* comes first. Motorola and Sparc processors store data in this
* format, while Intel processors store data in the reverse
* <code>ByteOrder.LITTLE_ENDIAN</code> order.
*
* <p> The byte order has no effect on the results returned from
* the <code>readBits</code> method (or the value written by
* <code>ImageOutputStream.writeBits</code>).
*
* @param byteOrder one of <code>ByteOrder.BIG_ENDIAN</code> or
* <code>java.nio.ByteOrder.LITTLE_ENDIAN</code>, indicating whether
* network byte order or its reverse will be used for future
* reads.
*
* @see java.nio.ByteOrder
* @see #getByteOrder
* @see #readBits(int)
*/
void setByteOrder(ByteOrder byteOrder);
/** {@collect.stats}
* Returns the byte order with which data values will be read from
* this stream as an instance of the
* <code>java.nio.ByteOrder</code> enumeration.
*
* @return one of <code>ByteOrder.BIG_ENDIAN</code> or
* <code>ByteOrder.LITTLE_ENDIAN</code>, indicating which byte
* order is being used.
*
* @see java.nio.ByteOrder
* @see #setByteOrder
*/
ByteOrder getByteOrder();
/** {@collect.stats}
* Reads a single byte from the stream and returns it as an
* integer between 0 and 255. If the end of the stream is
* reached, -1 is returned.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a byte value from the stream, as an int, or -1 to
* indicate EOF.
*
* @exception IOException if an I/O error occurs.
*/
int read() throws IOException;
/** {@collect.stats}
* Reads up to <code>b.length</code> bytes from the stream, and
* stores them into <code>b</code> starting at index 0. The
* number of bytes read is returned. If no bytes can be read
* because the end of the stream has been reached, -1 is returned.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param b an array of bytes to be written to.
*
* @return the number of bytes actually read, or <code>-1</code>
* to indicate EOF.
*
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
*
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b) throws IOException;
/** {@collect.stats}
* Reads up to <code>len</code> bytes from the stream, and stores
* them into <code>b</code> starting at index <code>off</code>.
* The number of bytes read is returned. If no bytes can be read
* because the end of the stream has been reached, <code>-1</code>
* is returned.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param b an array of bytes to be written to.
* @param off the starting position within <code>b</code> to write to.
* @param len the maximum number of <code>byte</code>s to read.
*
* @return the number of bytes actually read, or <code>-1</code>
* to indicate EOF.
*
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>b.length</code>.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/** {@collect.stats}
* Reads up to <code>len</code> bytes from the stream, and
* modifies the supplied <code>IIOByteBuffer</code> to indicate
* the byte array, offset, and length where the data may be found.
* The caller should not attempt to modify the data found in the
* <code>IIOByteBuffer</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param buf an IIOByteBuffer object to be modified.
* @param len the maximum number of <code>byte</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>len</code> is
* negative.
* @exception NullPointerException if <code>buf</code> is
* <code>null</code>.
*
* @exception IOException if an I/O error occurs.
*/
void readBytes(IIOByteBuffer buf, int len) throws IOException;
/** {@collect.stats}
* Reads a byte from the stream and returns a <code>boolean</code>
* value of <code>true</code> if it is nonzero, <code>false</code>
* if it is zero.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a boolean value from the stream.
*
* @exception EOFException if the end of the stream is reached.
* @exception IOException if an I/O error occurs.
*/
boolean readBoolean() throws IOException;
/** {@collect.stats}
* Reads a byte from the stream and returns it as a
* <code>byte</code> value. Byte values between <code>0x00</code>
* and <code>0x7f</code> represent integer values between
* <code>0</code> and <code>127</code>. Values between
* <code>0x80</code> and <code>0xff</code> represent negative
* values from <code>-128</code> to <code>/1</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a signed byte value from the stream.
*
* @exception EOFException if the end of the stream is reached.
* @exception IOException if an I/O error occurs.
*/
byte readByte() throws IOException;
/** {@collect.stats}
* Reads a byte from the stream, and (conceptually) converts it to
* an int, masks it with <code>0xff</code> in order to strip off
* any sign-extension bits, and returns it as a <code>byte</code>
* value.
*
* <p> Thus, byte values between <code>0x00</code> and
* <code>0x7f</code> are simply returned as integer values between
* <code>0</code> and <code>127</code>. Values between
* <code>0x80</code> and <code>0xff</code>, which normally
* represent negative <code>byte</code>values, will be mapped into
* positive integers between <code>128</code> and
* <code>255</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return an unsigned byte value from the stream.
*
* @exception EOFException if the end of the stream is reached.
* @exception IOException if an I/O error occurs.
*/
int readUnsignedByte() throws IOException;
/** {@collect.stats}
* Reads two bytes from the stream, and (conceptually)
* concatenates them according to the current byte order, and
* returns the result as a <code>short</code> value.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a signed short value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
short readShort() throws IOException;
/** {@collect.stats}
* Reads two bytes from the stream, and (conceptually)
* concatenates them according to the current byte order, converts
* the resulting value to an <code>int</code>, masks it with
* <code>0xffff</code> in order to strip off any sign-extension
* buts, and returns the result as an unsigned <code>int</code>
* value.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return an unsigned short value from the stream, as an int.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
int readUnsignedShort() throws IOException;
/** {@collect.stats}
* Equivalent to <code>readUnsignedShort</code>, except that the
* result is returned using the <code>char</code> datatype.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return an unsigned char value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #readUnsignedShort
*/
char readChar() throws IOException;
/** {@collect.stats}
* Reads 4 bytes from the stream, and (conceptually) concatenates
* them according to the current byte order and returns the result
* as an <code>int</code>.
*
* <p> The bit offset within the stream is ignored and treated as
* though it were zero.
*
* @return a signed int value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
int readInt() throws IOException;
/** {@collect.stats}
* Reads 4 bytes from the stream, and (conceptually) concatenates
* them according to the current byte order, converts the result
* to a long, masks it with <code>0xffffffffL</code> in order to
* strip off any sign-extension bits, and returns the result as an
* unsigned <code>long</code> value.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return an unsigned int value from the stream, as a long.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
long readUnsignedInt() throws IOException;
/** {@collect.stats}
* Reads 8 bytes from the stream, and (conceptually) concatenates
* them according to the current byte order and returns the result
* as a <code>long</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a signed long value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
long readLong() throws IOException;
/** {@collect.stats}
* Reads 4 bytes from the stream, and (conceptually) concatenates
* them according to the current byte order and returns the result
* as a <code>float</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a float value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
float readFloat() throws IOException;
/** {@collect.stats}
* Reads 8 bytes from the stream, and (conceptually) concatenates
* them according to the current byte order and returns the result
* as a <code>double</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a double value from the stream.
*
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*
* @see #getByteOrder
*/
double readDouble() throws IOException;
/** {@collect.stats}
* Reads the next line of text from the input stream. It reads
* successive bytes, converting each byte separately into a
* character, until it encounters a line terminator or end of
* file; the characters read are then returned as a
* <code>String</code>. Note that because this method processes
* bytes, it does not support input of the full Unicode character
* set.
*
* <p> If end of file is encountered before even one byte can be
* read, then <code>null</code> is returned. Otherwise, each byte
* that is read is converted to type <code>char</code> by
* zero-extension. If the character <code>'\n'</code> is
* encountered, it is discarded and reading ceases. If the
* character <code>'\r'</code> is encountered, it is discarded
* and, if the following byte converts  to the character
* <code>'\n'</code>, then that is discarded also; reading then
* ceases. If end of file is encountered before either of the
* characters <code>'\n'</code> and <code>'\r'</code> is
* encountered, reading ceases. Once reading has ceased, a
* <code>String</code> is returned that contains all the
* characters read and not discarded, taken in order. Note that
* every character in this string will have a value less than
* <code>\u0100</code>, that is, <code>(char)256</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return a String containing a line of text from the stream.
*
* @exception IOException if an I/O error occurs.
*/
String readLine() throws IOException;
/** {@collect.stats}
* Reads in a string that has been encoded using a
* <a href="../../../java/io/DataInput.html#modified-utf-8">modified
* UTF-8</a>
* format. The general contract of <code>readUTF</code> is that
* it reads a representation of a Unicode character string encoded
* in modified UTF-8 format; this string of characters is
* then returned as a <code>String</code>.
*
* <p> First, two bytes are read and used to construct an unsigned
* 16-bit integer in the manner of the
* <code>readUnsignedShort</code> method, using network byte order
* (regardless of the current byte order setting). This integer
* value is called the <i>UTF length</i> and specifies the number
* of additional bytes to be read. These bytes are then converted
* to characters by considering them in groups. The length of each
* group is computed from the value of the first byte of the
* group. The byte following a group, if any, is the first byte of
* the next group.
*
* <p> If the first byte of a group matches the bit pattern
* <code>0xxxxxxx</code> (where <code>x</code> means "may be
* <code>0</code> or <code>1</code>"), then the group consists of
* just that byte. The byte is zero-extended to form a character.
*
* <p> If the first byte of a group matches the bit pattern
* <code>110xxxxx</code>, then the group consists of that byte
* <code>a</code> and a second byte <code>b</code>. If there is no
* byte <code>b</code> (because byte <code>a</code> was the last
* of the bytes to be read), or if byte <code>b</code> does not
* match the bit pattern <code>10xxxxxx</code>, then a
* <code>UTFDataFormatException</code> is thrown. Otherwise, the
* group is converted to the character:
*
* <p> <pre><code>
* (char)(((a& 0x1F) << 6) | (b & 0x3F))
* </code></pre>
*
* If the first byte of a group matches the bit pattern
* <code>1110xxxx</code>, then the group consists of that byte
* <code>a</code> and two more bytes <code>b</code> and
* <code>c</code>. If there is no byte <code>c</code> (because
* byte <code>a</code> was one of the last two of the bytes to be
* read), or either byte <code>b</code> or byte <code>c</code>
* does not match the bit pattern <code>10xxxxxx</code>, then a
* <code>UTFDataFormatException</code> is thrown. Otherwise, the
* group is converted to the character:
*
* <p> <pre><code>
* (char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))
* </code></pre>
*
* If the first byte of a group matches the pattern
* <code>1111xxxx</code> or the pattern <code>10xxxxxx</code>,
* then a <code>UTFDataFormatException</code> is thrown.
*
* <p> If end of file is encountered at any time during this
* entire process, then an <code>EOFException</code> is thrown.
*
* <p> After every group has been converted to a character by this
* process, the characters are gathered, in the same order in
* which their corresponding groups were read from the input
* stream, to form a <code>String</code>, which is returned.
*
* <p> The current byte order setting is ignored.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* <p><strong>Note:</strong> This method should not be used in
* the implementation of image formats that use standard UTF-8,
* because the modified UTF-8 used here is incompatible with
* standard UTF-8.
*
* @return a String read from the stream.
*
* @exception EOFException if this stream reaches the end
* before reading all the bytes.
* @exception UTFDataFormatException if the bytes do not represent a
* valid modified UTF-8 encoding of a string.
* @exception IOException if an I/O error occurs.
*/
String readUTF() throws IOException;
/** {@collect.stats}
* Reads <code>len</code> bytes from the stream, and stores them
* into <code>b</code> starting at index <code>off</code>.
* If the end of the stream is reached, an <code>EOFException</code>
* will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param b an array of bytes to be written to.
* @param off the starting position within <code>b</code> to write to.
* @param len the maximum number of <code>byte</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>b.length</code>.
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(byte[] b, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>b.length</code> bytes from the stream, and stores them
* into <code>b</code> starting at index <code>0</code>.
* If the end of the stream is reached, an <code>EOFException</code>
* will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param b an array of <code>byte</code>s.
*
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(byte[] b) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> shorts (signed 16-bit integers) from the
* stream according to the current byte order, and
* stores them into <code>s</code> starting at index
* <code>off</code>. If the end of the stream is reached, an
* <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param s an array of shorts to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>short</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>s.length</code>.
* @exception NullPointerException if <code>s</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(short[] s, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> chars (unsigned 16-bit integers) from the
* stream according to the current byte order, and
* stores them into <code>c</code> starting at index
* <code>off</code>. If the end of the stream is reached, an
* <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param c an array of chars to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>char</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>c.length</code>.
* @exception NullPointerException if <code>c</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(char[] c, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> ints (signed 32-bit integers) from the
* stream according to the current byte order, and
* stores them into <code>i</code> starting at index
* <code>off</code>. If the end of the stream is reached, an
* <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param i an array of ints to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>int</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>i.length</code>.
* @exception NullPointerException if <code>i</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(int[] i, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> longs (signed 64-bit integers) from the
* stream according to the current byte order, and
* stores them into <code>l</code> starting at index
* <code>off</code>. If the end of the stream is reached, an
* <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param l an array of longs to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>long</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>l.length</code>.
* @exception NullPointerException if <code>l</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(long[] l, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> floats (32-bit IEEE single-precision
* floats) from the stream according to the current byte order,
* and stores them into <code>f</code> starting at
* index <code>off</code>. If the end of the stream is reached,
* an <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param f an array of floats to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>float</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>f.length</code>.
* @exception NullPointerException if <code>f</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(float[] f, int off, int len) throws IOException;
/** {@collect.stats}
* Reads <code>len</code> doubles (64-bit IEEE double-precision
* floats) from the stream according to the current byte order,
* and stores them into <code>d</code> starting at
* index <code>off</code>. If the end of the stream is reached,
* an <code>EOFException</code> will be thrown.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @param d an array of doubles to be written to.
* @param off the starting position withinb to write to.
* @param len the maximum number of <code>double</code>s to read.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>d.length</code>.
* @exception NullPointerException if <code>d</code> is
* <code>null</code>.
* @exception EOFException if the stream reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
*/
void readFully(double[] d, int off, int len) throws IOException;
/** {@collect.stats}
* Returns the current byte position of the stream. The next read
* will take place starting at this offset.
*
* @return a long containing the position of the stream.
*
* @exception IOException if an I/O error occurs.
*/
long getStreamPosition() throws IOException;
/** {@collect.stats}
* Returns the current bit offset, as an integer between 0 and 7,
* inclusive. The bit offset is updated implicitly by calls to
* the <code>readBits</code> method. A value of 0 indicates the
* most-significant bit, and a value of 7 indicates the least
* significant bit, of the byte being read.
*
* <p> The bit offset is set to 0 when a stream is first
* opened, and is reset to 0 by calls to <code>seek</code>,
* <code>skipBytes</code>, or any <code>read</code> or
* <code>readFully</code> method.
*
* @return an <code>int</code> containing the bit offset between
* 0 and 7, inclusive.
*
* @exception IOException if an I/O error occurs.
*
* @see #setBitOffset
*/
int getBitOffset() throws IOException;
/** {@collect.stats}
* Sets the bit offset to an integer between 0 and 7, inclusive.
* The byte offset within the stream, as returned by
* <code>getStreamPosition</code>, is left unchanged.
* A value of 0 indicates the
* most-significant bit, and a value of 7 indicates the least
* significant bit, of the byte being read.
*
* @param bitOffset the desired offset, as an <code>int</code>
* between 0 and 7, inclusive.
*
* @exception IllegalArgumentException if <code>bitOffset</code>
* is not between 0 and 7, inclusive.
* @exception IOException if an I/O error occurs.
*
* @see #getBitOffset
*/
void setBitOffset(int bitOffset) throws IOException;
/** {@collect.stats}
* Reads a single bit from the stream and returns it as an
* <code>int</code> with the value <code>0</code> or
* <code>1</code>. The bit offset is advanced by one and reduced
* modulo 8.
*
* @return an <code>int</code> containing the value <code>0</code>
* or <code>1</code>.
*
* @exception EOFException if the stream reaches the end before
* reading all the bits.
* @exception IOException if an I/O error occurs.
*/
int readBit() throws IOException;
/** {@collect.stats}
* Reads a bitstring from the stream and returns it as a
* <code>long</code>, with the first bit read becoming the most
* significant bit of the output. The read starts within the byte
* indicated by <code>getStreamPosition</code>, at the bit given
* by <code>getBitOffset</code>. The bit offset is advanced by
* <code>numBits</code> and reduced modulo 8.
*
* <p> The byte order of the stream has no effect on this
* method. The return value of this method is constructed as
* though the bits were read one at a time, and shifted into
* the right side of the return value, as shown by the following
* pseudo-code:
*
* <pre>
* long accum = 0L;
* for (int i = 0; i < numBits; i++) {
* accum <<= 1; // Shift left one bit to make room
* accum |= readBit();
* }
* </pre>
*
* Note that the result of <code>readBits(32)</code> may thus not
* be equal to that of <code>readInt()</code> if a reverse network
* byte order is being used (i.e., <code>getByteOrder() ==
* false</code>).
*
* <p> If the end of the stream is encountered before all the bits
* have been read, an <code>EOFException</code> is thrown.
*
* @param numBits the number of bits to read, as an <code>int</code>
* between 0 and 64, inclusive.
* @return the bitstring, as a <code>long</code> with the last bit
* read stored in the least significant bit.
*
* @exception IllegalArgumentException if <code>numBits</code>
* is not between 0 and 64, inclusive.
* @exception EOFException if the stream reaches the end before
* reading all the bits.
* @exception IOException if an I/O error occurs.
*/
long readBits(int numBits) throws IOException;
/** {@collect.stats}
* Returns the total length of the stream, if known. Otherwise,
* <code>-1</code> is returned.
*
* @return a <code>long</code> containing the length of the
* stream, if known, or else <code>-1</code>.
*
* @exception IOException if an I/O error occurs.
*/
long length() throws IOException;
/** {@collect.stats}
* Moves the stream position forward by a given number of bytes. It
* is possible that this method will only be able to skip forward
* by a smaller number of bytes than requested, for example if the
* end of the stream is reached. In all cases, the actual number
* of bytes skipped is returned. The bit offset is set to zero
* prior to advancing the position.
*
* @param n an <code>int</code> containing the number of bytes to
* be skipped.
*
* @return an <code>int</code> representing the number of bytes skipped.
*
* @exception IOException if an I/O error occurs.
*/
int skipBytes(int n) throws IOException;
/** {@collect.stats}
* Moves the stream position forward by a given number of bytes.
* This method is identical to <code>skipBytes(int)</code> except
* that it allows for a larger skip distance.
*
* @param n a <code>long</code> containing the number of bytes to
* be skipped.
*
* @return a <code>long</code> representing the number of bytes
* skipped.
*
* @exception IOException if an I/O error occurs.
*/
long skipBytes(long n) throws IOException;
/** {@collect.stats}
* Sets the current stream position to the desired location. The
* next read will occur at this location. The bit offset is set
* to 0.
*
* <p> An <code>IndexOutOfBoundsException</code> will be thrown if
* <code>pos</code> is smaller than the flushed position (as
* returned by <code>getflushedPosition</code>).
*
* <p> It is legal to seek past the end of the file; an
* <code>EOFException</code> will be thrown only if a read is
* performed.
*
* @param pos a <code>long</code> containing the desired file
* pointer position.
*
* @exception IndexOutOfBoundsException if <code>pos</code> is smaller
* than the flushed position.
* @exception IOException if any other I/O error occurs.
*/
void seek(long pos) throws IOException;
/** {@collect.stats}
* Marks a position in the stream to be returned to by a
* subsequent call to <code>reset</code>. Unlike a standard
* <code>InputStream</code>, all <code>ImageInputStream</code>s
* support marking. Additionally, calls to <code>mark</code> and
* <code>reset</code> may be nested arbitrarily.
*
* <p> Unlike the <code>mark</code> methods declared by the
* <code>Reader</code> and <code>InputStream</code> interfaces, no
* <code>readLimit</code> parameter is used. An arbitrary amount
* of data may be read following the call to <code>mark</code>.
*
* <p> The bit position used by the <code>readBits</code> method
* is saved and restored by each pair of calls to
* <code>mark</code> and <code>reset</code>.
*
* <p> Note that it is valid for an <code>ImageReader</code> to call
* <code>flushBefore</code> as part of a read operation.
* Therefore, if an application calls <code>mark</code> prior to
* passing that stream to an <code>ImageReader</code>, the application
* should not assume that the marked position will remain valid after
* the read operation has completed.
*/
void mark();
/** {@collect.stats}
* Returns the stream pointer to its previous position, including
* the bit offset, at the time of the most recent unmatched call
* to <code>mark</code>.
*
* <p> Calls to <code>reset</code> without a corresponding call
* to <code>mark</code> have no effect.
*
* <p> An <code>IOException</code> will be thrown if the previous
* marked position lies in the discarded portion of the stream.
*
* @exception IOException if an I/O error occurs.
*/
void reset() throws IOException;
/** {@collect.stats}
* Discards the initial portion of the stream prior to the
* indicated postion. Attempting to seek to an offset within the
* flushed portion of the stream will result in an
* <code>IndexOutOfBoundsException</code>.
*
* <p> Calling <code>flushBefore</code> may allow classes
* implementing this interface to free up resources such as memory
* or disk space that are being used to store data from the
* stream.
*
* @param pos a <code>long</code> containing the length of the
* stream prefix that may be flushed.
*
* @exception IndexOutOfBoundsException if <code>pos</code> lies
* in the flushed portion of the stream or past the current stream
* position.
* @exception IOException if an I/O error occurs.
*/
void flushBefore(long pos) throws IOException;
/** {@collect.stats}
* Discards the initial position of the stream prior to the current
* stream position. Equivalent to
* <code>flushBefore(getStreamPosition())</code>.
*
* @exception IOException if an I/O error occurs.
*/
void flush() throws IOException;
/** {@collect.stats}
* Returns the earliest position in the stream to which seeking
* may be performed. The returned value will be the maximum of
* all values passed into previous calls to
* <code>flushBefore</code>.
*
* @return the earliest legal position for seeking, as a
* <code>long</code>.
*/
long getFlushedPosition();
/** {@collect.stats}
* Returns <code>true</code> if this <code>ImageInputStream</code>
* caches data itself in order to allow seeking backwards.
* Applications may consult this in order to decide how frequently,
* or whether, to flush in order to conserve cache resources.
*
* @return <code>true</code> if this <code>ImageInputStream</code>
* caches data.
*
* @see #isCachedMemory
* @see #isCachedFile
*/
boolean isCached();
/** {@collect.stats}
* Returns <code>true</code> if this <code>ImageInputStream</code>
* caches data itself in order to allow seeking backwards, and
* the cache is kept in main memory. Applications may consult
* this in order to decide how frequently, or whether, to flush
* in order to conserve cache resources.
*
* @return <code>true</code> if this <code>ImageInputStream</code>
* caches data in main memory.
*
* @see #isCached
* @see #isCachedFile
*/
boolean isCachedMemory();
/** {@collect.stats}
* Returns <code>true</code> if this <code>ImageInputStream</code>
* caches data itself in order to allow seeking backwards, and
* the cache is kept in a temporary file. Applications may consult
* this in order to decide how frequently, or whether, to flush
* in order to conserve cache resources.
*
* @return <code>true</code> if this <code>ImageInputStream</code>
* caches data in a temporary file.
*
* @see #isCached
* @see #isCachedMemory
*/
boolean isCachedFile();
/** {@collect.stats}
* Closes the stream. Attempts to access a stream that has been
* closed may result in <code>IOException</code>s or incorrect
* behavior. Calling this method may allow classes implementing
* this interface to release resources associated with the stream
* such as memory, disk space, or file descriptors.
*
* @exception IOException if an I/O error occurs.
*/
void close() throws IOException;
}
|
Java
|
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
/** {@collect.stats}
* Package-visible class consolidating common code for
* <code>MemoryCacheImageInputStream</code> and
* <code>MemoryCacheImageOutputStream</code>.
* This class keeps an <code>ArrayList</code> of 8K blocks,
* loaded sequentially. Blocks may only be disposed of
* from the index 0 forward. As blocks are freed, the
* corresponding entries in the array list are set to
* <code>null</code>, but no compacting is performed.
* This allows the index for each block to never change,
* and the length of the cache is always the same as the
* total amount of data ever cached. Cached data is
* therefore always contiguous from the point of last
* disposal to the current length.
*
* <p> The total number of blocks resident in the cache must not
* exceed <code>Integer.MAX_VALUE</code>. In practice, the limit of
* available memory will be exceeded long before this becomes an
* issue, since a full cache would contain 8192*2^31 = 16 terabytes of
* data.
*
* A <code>MemoryCache</code> may be reused after a call
* to <code>reset()</code>.
*/
class MemoryCache {
private static final int BUFFER_LENGTH = 8192;
private ArrayList cache = new ArrayList();
private long cacheStart = 0L;
/** {@collect.stats}
* The largest position ever written to the cache.
*/
private long length = 0L;
private byte[] getCacheBlock(long blockNum) throws IOException {
long blockOffset = blockNum - cacheStart;
if (blockOffset > Integer.MAX_VALUE) {
// This can only happen when the cache hits 16 terabytes of
// contiguous data...
throw new IOException("Cache addressing limit exceeded!");
}
return (byte[])cache.get((int)blockOffset);
}
/** {@collect.stats}
* Ensures that at least <code>pos</code> bytes are cached,
* or the end of the source is reached. The return value
* is equal to the smaller of <code>pos</code> and the
* length of the source.
*/
public long loadFromStream(InputStream stream, long pos)
throws IOException {
// We've already got enough data cached
if (pos < length) {
return pos;
}
int offset = (int)(length % BUFFER_LENGTH);
byte [] buf = null;
long len = pos - length;
if (offset != 0) {
buf = getCacheBlock(length/BUFFER_LENGTH);
}
while (len > 0) {
if (buf == null) {
try {
buf = new byte[BUFFER_LENGTH];
} catch (OutOfMemoryError e) {
throw new IOException("No memory left for cache!");
}
offset = 0;
}
int left = BUFFER_LENGTH - offset;
int nbytes = (int)Math.min(len, (long)left);
nbytes = stream.read(buf, offset, nbytes);
if (nbytes == -1) {
return length; // EOF
}
if (offset == 0) {
cache.add(buf);
}
len -= nbytes;
length += nbytes;
offset += nbytes;
if (offset >= BUFFER_LENGTH) {
// we've filled the current buffer, so a new one will be
// allocated next time around (and offset will be reset to 0)
buf = null;
}
}
return pos;
}
/** {@collect.stats}
* Writes out a portion of the cache to an <code>OutputStream</code>.
* This method preserves no state about the output stream, and does
* not dispose of any blocks containing bytes written. To dispose
* blocks, use {@link #disposeBefore <code>disposeBefore()</code>}.
*
* @exception IndexOutOfBoundsException if any portion of
* the requested data is not in the cache (including if <code>pos</code>
* is in a block already disposed), or if either <code>pos</code> or
* <code>len</code> is < 0.
*/
public void writeToStream(OutputStream stream, long pos, long len)
throws IOException {
if (pos + len > length) {
throw new IndexOutOfBoundsException("Argument out of cache");
}
if ((pos < 0) || (len < 0)) {
throw new IndexOutOfBoundsException("Negative pos or len");
}
if (len == 0) {
return;
}
long bufIndex = pos/BUFFER_LENGTH;
if (bufIndex < cacheStart) {
throw new IndexOutOfBoundsException("pos already disposed");
}
int offset = (int)(pos % BUFFER_LENGTH);
byte[] buf = getCacheBlock(bufIndex++);
while (len > 0) {
if (buf == null) {
buf = getCacheBlock(bufIndex++);
offset = 0;
}
int nbytes = (int)Math.min(len, (long)(BUFFER_LENGTH - offset));
stream.write(buf, offset, nbytes);
buf = null;
len -= nbytes;
}
}
/** {@collect.stats}
* Ensure that there is space to write a byte at the given position.
*/
private void pad(long pos) throws IOException {
long currIndex = cacheStart + cache.size() - 1;
long lastIndex = pos/BUFFER_LENGTH;
long numNewBuffers = lastIndex - currIndex;
for (long i = 0; i < numNewBuffers; i++) {
try {
cache.add(new byte[BUFFER_LENGTH]);
} catch (OutOfMemoryError e) {
throw new IOException("No memory left for cache!");
}
}
}
/** {@collect.stats}
* Overwrites and/or appends the cache from a byte array.
* The length of the cache will be extended as needed to hold
* the incoming data.
*
* @param b an array of bytes containing data to be written.
* @param off the starting offset withing the data array.
* @param len the number of bytes to be written.
* @param pos the cache position at which to begin writing.
*
* @exception NullPointerException if <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException if <code>off</code>,
* <code>len</code>, or <code>pos</code> are negative,
* or if <code>off+len > b.length</code>.
*/
public void write(byte[] b, int off, int len, long pos)
throws IOException {
if (b == null) {
throw new NullPointerException("b == null!");
}
// Fix 4430357 - if off + len < 0, overflow occurred
if ((off < 0) || (len < 0) || (pos < 0) ||
(off + len > b.length) || (off + len < 0)) {
throw new IndexOutOfBoundsException();
}
// Ensure there is space for the incoming data
long lastPos = pos + len - 1;
if (lastPos >= length) {
pad(lastPos);
length = lastPos + 1;
}
// Copy the data into the cache, block by block
int offset = (int)(pos % BUFFER_LENGTH);
while (len > 0) {
byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);
int nbytes = Math.min(len, BUFFER_LENGTH - offset);
System.arraycopy(b, off, buf, offset, nbytes);
pos += nbytes;
off += nbytes;
len -= nbytes;
offset = 0; // Always after the first time
}
}
/** {@collect.stats}
* Overwrites or appends a single byte to the cache.
* The length of the cache will be extended as needed to hold
* the incoming data.
*
* @param b an <code>int</code> whose 8 least significant bits
* will be written.
* @param pos the cache position at which to begin writing.
*
* @exception IndexOutOfBoundsException if <code>pos</code> is negative.
*/
public void write(int b, long pos) throws IOException {
if (pos < 0) {
throw new ArrayIndexOutOfBoundsException("pos < 0");
}
// Ensure there is space for the incoming data
if (pos >= length) {
pad(pos);
length = pos + 1;
}
// Insert the data.
byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);
int offset = (int)(pos % BUFFER_LENGTH);
buf[offset] = (byte)b;
}
/** {@collect.stats}
* Returns the total length of data that has been cached,
* regardless of whether any early blocks have been disposed.
* This value will only ever increase.
*/
public long getLength() {
return length;
}
/** {@collect.stats}
* Returns the single byte at the given position, as an
* <code>int</code>. Returns -1 if this position has
* not been cached or has been disposed.
*/
public int read(long pos) throws IOException {
if (pos >= length) {
return -1;
}
byte[] buf = getCacheBlock(pos/BUFFER_LENGTH);
if (buf == null) {
return -1;
}
return buf[(int)(pos % BUFFER_LENGTH)] & 0xff;
}
/** {@collect.stats}
* Copy <code>len</code> bytes from the cache, starting
* at cache position <code>pos</code>, into the array
* <code>b</code> at offset <code>off</code>.
*
* @exception NullPointerException if b is <code>null</code>
* @exception IndexOutOfBoundsException if <code>off</code>,
* <code>len</code> or <code>pos</code> are negative or if
* <code>off + len > b.length</code> or if any portion of the
* requested data is not in the cache (including if
* <code>pos</code> is in a block that has already been disposed).
*/
public void read(byte[] b, int off, int len, long pos)
throws IOException {
if (b == null) {
throw new NullPointerException("b == null!");
}
// Fix 4430357 - if off + len < 0, overflow occurred
if ((off < 0) || (len < 0) || (pos < 0) ||
(off + len > b.length) || (off + len < 0)) {
throw new IndexOutOfBoundsException();
}
if (pos + len > length) {
throw new IndexOutOfBoundsException();
}
long index = pos/BUFFER_LENGTH;
int offset = (int)pos % BUFFER_LENGTH;
while (len > 0) {
int nbytes = Math.min(len, BUFFER_LENGTH - offset);
byte[] buf = getCacheBlock(index++);
System.arraycopy(buf, offset, b, off, nbytes);
len -= nbytes;
off += nbytes;
offset = 0; // Always after the first time
}
}
/** {@collect.stats}
* Free the blocks up to the position <code>pos</code>.
* The byte at <code>pos</code> remains available.
*
* @exception IndexOutOfBoundsException if <code>pos</code>
* is in a block that has already been disposed.
*/
public void disposeBefore(long pos) {
long index = pos/BUFFER_LENGTH;
if (index < cacheStart) {
throw new IndexOutOfBoundsException("pos already disposed");
}
long numBlocks = Math.min(index - cacheStart, cache.size());
for (long i = 0; i < numBlocks; i++) {
cache.remove(0);
}
this.cacheStart = index;
}
/** {@collect.stats}
* Erase the entire cache contents and reset the length to 0.
* The cache object may subsequently be reused as though it had just
* been allocated.
*/
public void reset() {
cache.clear();
cacheStart = 0;
length = 0L;
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.sun.imageio.stream.CloseableDisposerRecord;
import com.sun.imageio.stream.StreamFinalizer;
import sun.java2d.Disposer;
/** {@collect.stats}
* An implementation of <code>ImageInputStream</code> that gets its
* input from a <code>File</code> or <code>RandomAccessFile</code>.
* The file contents are assumed to be stable during the lifetime of
* the object.
*
*/
public class FileImageInputStream extends ImageInputStreamImpl {
private RandomAccessFile raf;
/** {@collect.stats} The referent to be registered with the Disposer. */
private final Object disposerReferent;
/** {@collect.stats} The DisposerRecord that closes the underlying RandomAccessFile. */
private final CloseableDisposerRecord disposerRecord;
/** {@collect.stats}
* Constructs a <code>FileImageInputStream</code> that will read
* from a given <code>File</code>.
*
* <p> The file contents must not change between the time this
* object is constructed and the time of the last call to a read
* method.
*
* @param f a <code>File</code> to read from.
*
* @exception IllegalArgumentException if <code>f</code> is
* <code>null</code>.
* @exception SecurityException if a security manager exists
* and does not allow read access to the file.
* @exception FileNotFoundException if <code>f</code> is a
* directory or cannot be opened for reading for any other reason.
* @exception IOException if an I/O error occurs.
*/
public FileImageInputStream(File f)
throws FileNotFoundException, IOException {
this(f == null ? null : new RandomAccessFile(f, "r"));
}
/** {@collect.stats}
* Constructs a <code>FileImageInputStream</code> that will read
* from a given <code>RandomAccessFile</code>.
*
* <p> The file contents must not change between the time this
* object is constructed and the time of the last call to a read
* method.
*
* @param raf a <code>RandomAccessFile</code> to read from.
*
* @exception IllegalArgumentException if <code>raf</code> is
* <code>null</code>.
*/
public FileImageInputStream(RandomAccessFile raf) {
if (raf == null) {
throw new IllegalArgumentException("raf == null!");
}
this.raf = raf;
disposerRecord = new CloseableDisposerRecord(raf);
if (getClass() == FileImageInputStream.class) {
disposerReferent = new Object();
Disposer.addRecord(disposerReferent, disposerRecord);
} else {
disposerReferent = new StreamFinalizer(this);
}
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
int val = raf.read();
if (val != -1) {
++streamPos;
}
return val;
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
bitOffset = 0;
int nbytes = raf.read(b, off, len);
if (nbytes != -1) {
streamPos += nbytes;
}
return nbytes;
}
/** {@collect.stats}
* Returns the length of the underlying file, or <code>-1</code>
* if it is unknown.
*
* @return the file length as a <code>long</code>, or
* <code>-1</code>.
*/
public long length() {
try {
checkClosed();
return raf.length();
} catch (IOException e) {
return -1L;
}
}
public void seek(long pos) throws IOException {
checkClosed();
if (pos < flushedPos) {
throw new IndexOutOfBoundsException("pos < flushedPos!");
}
bitOffset = 0;
raf.seek(pos);
streamPos = raf.getFilePointer();
}
public void close() throws IOException {
super.close();
disposerRecord.dispose(); // this closes the RandomAccessFile
raf = null;
}
/** {@collect.stats}
* {@inheritDoc}
*/
protected void finalize() throws Throwable {
// Empty finalizer: for performance reasons we instead use the
// Disposer mechanism for ensuring that the underlying
// RandomAccessFile is closed prior to garbage collection
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.IOException;
import java.io.UTFDataFormatException;
import java.nio.ByteOrder;
/** {@collect.stats}
* An abstract class implementing the <code>ImageOutputStream</code> interface.
* This class is designed to reduce the number of methods that must
* be implemented by subclasses.
*
*/
public abstract class ImageOutputStreamImpl
extends ImageInputStreamImpl
implements ImageOutputStream {
/** {@collect.stats}
* Constructs an <code>ImageOutputStreamImpl</code>.
*/
public ImageOutputStreamImpl() {
}
public abstract void write(int b) throws IOException;
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public abstract void write(byte b[], int off, int len) throws IOException;
public void writeBoolean(boolean v) throws IOException {
write(v ? 1 : 0);
}
public void writeByte(int v) throws IOException {
write(v);
}
public void writeShort(int v) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
byteBuf[0] = (byte)(v >>> 8);
byteBuf[1] = (byte)(v >>> 0);
} else {
byteBuf[0] = (byte)(v >>> 0);
byteBuf[1] = (byte)(v >>> 8);
}
write(byteBuf, 0, 2);
}
public void writeChar(int v) throws IOException {
writeShort(v);
}
public void writeInt(int v) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
byteBuf[0] = (byte)(v >>> 24);
byteBuf[1] = (byte)(v >>> 16);
byteBuf[2] = (byte)(v >>> 8);
byteBuf[3] = (byte)(v >>> 0);
} else {
byteBuf[0] = (byte)(v >>> 0);
byteBuf[1] = (byte)(v >>> 8);
byteBuf[2] = (byte)(v >>> 16);
byteBuf[3] = (byte)(v >>> 24);
}
write(byteBuf, 0, 4);
}
public void writeLong(long v) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
byteBuf[0] = (byte)(v >>> 56);
byteBuf[1] = (byte)(v >>> 48);
byteBuf[2] = (byte)(v >>> 40);
byteBuf[3] = (byte)(v >>> 32);
byteBuf[4] = (byte)(v >>> 24);
byteBuf[5] = (byte)(v >>> 16);
byteBuf[6] = (byte)(v >>> 8);
byteBuf[7] = (byte)(v >>> 0);
} else {
byteBuf[0] = (byte)(v >>> 0);
byteBuf[1] = (byte)(v >>> 8);
byteBuf[2] = (byte)(v >>> 16);
byteBuf[3] = (byte)(v >>> 24);
byteBuf[4] = (byte)(v >>> 32);
byteBuf[5] = (byte)(v >>> 40);
byteBuf[6] = (byte)(v >>> 48);
byteBuf[7] = (byte)(v >>> 56);
}
// REMIND: Once 6277756 is fixed, we should do a bulk write of all 8
// bytes here as we do in writeShort() and writeInt() for even better
// performance. For now, two bulk writes of 4 bytes each is still
// faster than 8 individual write() calls (see 6347575 for details).
write(byteBuf, 0, 4);
write(byteBuf, 4, 4);
}
public void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
public void writeBytes(String s) throws IOException {
int len = s.length();
for (int i = 0 ; i < len ; i++) {
write((byte)s.charAt(i));
}
}
public void writeChars(String s) throws IOException {
int len = s.length();
byte[] b = new byte[len*2];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len ; i++) {
int v = s.charAt(i);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len ; i++) {
int v = s.charAt(i);
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
}
}
write(b, 0, len*2);
}
public void writeUTF(String s) throws IOException {
int strlen = s.length();
int utflen = 0;
char[] charr = new char[strlen];
int c, boff = 0;
s.getChars(0, strlen, charr, 0);
for (int i = 0; i < strlen; i++) {
c = charr[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
} else if (c > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
if (utflen > 65535) {
throw new UTFDataFormatException("utflen > 65536!");
}
byte[] b = new byte[utflen+2];
b[boff++] = (byte) ((utflen >>> 8) & 0xFF);
b[boff++] = (byte) ((utflen >>> 0) & 0xFF);
for (int i = 0; i < strlen; i++) {
c = charr[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
b[boff++] = (byte) c;
} else if (c > 0x07FF) {
b[boff++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
b[boff++] = (byte) (0x80 | ((c >> 6) & 0x3F));
b[boff++] = (byte) (0x80 | ((c >> 0) & 0x3F));
} else {
b[boff++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
b[boff++] = (byte) (0x80 | ((c >> 0) & 0x3F));
}
}
write(b, 0, utflen + 2);
}
public void writeShorts(short[] s, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > s.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > s.length!");
}
byte[] b = new byte[len*2];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len; i++) {
short v = s[off + i];
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len; i++) {
short v = s[off + i];
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
}
}
write(b, 0, len*2);
}
public void writeChars(char[] c, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > c.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > c.length!");
}
byte[] b = new byte[len*2];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len; i++) {
char v = c[off + i];
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len; i++) {
char v = c[off + i];
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
}
}
write(b, 0, len*2);
}
public void writeInts(int[] i, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > i.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > i.length!");
}
byte[] b = new byte[len*4];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int v = i[off + j];
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int j = 0; j < len; j++) {
int v = i[off + j];
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 24);
}
}
write(b, 0, len*4);
}
public void writeLongs(long[] l, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > l.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > l.length!");
}
byte[] b = new byte[len*8];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len; i++) {
long v = l[off + i];
b[boff++] = (byte)(v >>> 56);
b[boff++] = (byte)(v >>> 48);
b[boff++] = (byte)(v >>> 40);
b[boff++] = (byte)(v >>> 32);
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len; i++) {
long v = l[off + i];
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 32);
b[boff++] = (byte)(v >>> 40);
b[boff++] = (byte)(v >>> 48);
b[boff++] = (byte)(v >>> 56);
}
}
write(b, 0, len*8);
}
public void writeFloats(float[] f, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > f.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > f.length!");
}
byte[] b = new byte[len*4];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len; i++) {
int v = Float.floatToIntBits(f[off + i]);
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len; i++) {
int v = Float.floatToIntBits(f[off + i]);
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 24);
}
}
write(b, 0, len*4);
}
public void writeDoubles(double[] d, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > d.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > d.length!");
}
byte[] b = new byte[len*8];
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int i = 0; i < len; i++) {
long v = Double.doubleToLongBits(d[off + i]);
b[boff++] = (byte)(v >>> 56);
b[boff++] = (byte)(v >>> 48);
b[boff++] = (byte)(v >>> 40);
b[boff++] = (byte)(v >>> 32);
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 0);
}
} else {
for (int i = 0; i < len; i++) {
long v = Double.doubleToLongBits(d[off + i]);
b[boff++] = (byte)(v >>> 0);
b[boff++] = (byte)(v >>> 8);
b[boff++] = (byte)(v >>> 16);
b[boff++] = (byte)(v >>> 24);
b[boff++] = (byte)(v >>> 32);
b[boff++] = (byte)(v >>> 40);
b[boff++] = (byte)(v >>> 48);
b[boff++] = (byte)(v >>> 56);
}
}
write(b, 0, len*8);
}
public void writeBit(int bit) throws IOException {
writeBits((1L & bit), 1);
}
public void writeBits(long bits, int numBits) throws IOException {
checkClosed();
if (numBits < 0 || numBits > 64) {
throw new IllegalArgumentException("Bad value for numBits!");
}
if (numBits == 0) {
return;
}
// Prologue: deal with pre-existing bits
// Bug 4499158, 4507868 - if we're at the beginning of the stream
// and the bit offset is 0, there can't be any pre-existing bits
if ((getStreamPosition() > 0) || (bitOffset > 0)) {
int offset = bitOffset; // read() will reset bitOffset
int partialByte = read();
if (partialByte != -1) {
seek(getStreamPosition() - 1);
} else {
partialByte = 0;
}
if (numBits + offset < 8) {
// Notch out the partial byte and drop in the new bits
int shift = 8 - (offset+numBits);
int mask = -1 >>> (32 - numBits);
partialByte &= ~(mask << shift); // Clear out old bits
partialByte |= ((bits & mask) << shift); // Or in new ones
write(partialByte);
seek(getStreamPosition() - 1);
bitOffset = offset + numBits;
numBits = 0; // Signal that we are done
} else {
// Fill out the partial byte and reduce numBits
int num = 8 - offset;
int mask = -1 >>> (32 - num);
partialByte &= ~mask; // Clear out bits
partialByte |= ((bits >> (numBits - num)) & mask);
// Note that bitOffset is already 0, so there is no risk
// of this advancing to the next byte
write(partialByte);
numBits -= num;
}
}
// Now write any whole bytes
if (numBits > 7) {
int extra = numBits % 8;
for (int numBytes = numBits / 8; numBytes > 0; numBytes--) {
int shift = (numBytes-1)*8+extra;
int value = (int) ((shift == 0)
? bits & 0xFF
: (bits>>shift) & 0xFF);
write(value);
}
numBits = extra;
}
// Epilogue: write out remaining partial byte, if any
// Note that we may be at EOF, in which case we pad with 0,
// or not, in which case we must preserve the existing bits
if (numBits != 0) {
// If we are not at the end of the file, read the current byte
// If we are at the end of the file, initialize our byte to 0.
int partialByte = 0;
partialByte = read();
if (partialByte != -1) {
seek(getStreamPosition() - 1);
}
// Fix 4494976: writeBit(int) does not pad the remainder
// of the current byte with 0s
else { // EOF
partialByte = 0;
}
int shift = 8 - numBits;
int mask = -1 >>> (32 - numBits);
partialByte &= ~(mask << shift);
partialByte |= (bits & mask) << shift;
// bitOffset is always already 0 when we get here.
write(partialByte);
seek(getStreamPosition() - 1);
bitOffset = numBits;
}
}
/** {@collect.stats}
* If the bit offset is non-zero, forces the remaining bits
* in the current byte to 0 and advances the stream position
* by one. This method should be called by subclasses at the
* beginning of the <code>write(int)</code> and
* <code>write(byte[], int, int)</code> methods.
*
* @exception IOException if an I/O error occurs.
*/
protected final void flushBits() throws IOException {
checkClosed();
if (bitOffset != 0) {
int offset = bitOffset;
int partialByte = read(); // Sets bitOffset to 0
if (partialByte < 0) {
// Fix 4465683: When bitOffset is set
// to something non-zero beyond EOF,
// we should set that whole byte to
// zero and write it to stream.
partialByte = 0;
bitOffset = 0;
}
else {
seek(getStreamPosition() - 1);
partialByte &= -1 << (8 - offset);
}
write(partialByte);
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.Stack;
import javax.imageio.IIOException;
/** {@collect.stats}
* An abstract class implementing the <code>ImageInputStream</code> interface.
* This class is designed to reduce the number of methods that must
* be implemented by subclasses.
*
* <p> In particular, this class handles most or all of the details of
* byte order interpretation, buffering, mark/reset, discarding,
* closing, and disposing.
*/
public abstract class ImageInputStreamImpl implements ImageInputStream {
private Stack markByteStack = new Stack();
private Stack markBitStack = new Stack();
private boolean isClosed = false;
// Length of the buffer used for readFully(type[], int, int)
private static final int BYTE_BUF_LENGTH = 8192;
/** {@collect.stats}
* Byte buffer used for readFully(type[], int, int). Note that this
* array is also used for bulk reads in readShort(), readInt(), etc, so
* it should be large enough to hold a primitive value (i.e. >= 8 bytes).
* Also note that this array is package protected, so that it can be
* used by ImageOutputStreamImpl in a similar manner.
*/
byte[] byteBuf = new byte[BYTE_BUF_LENGTH];
/** {@collect.stats}
* The byte order of the stream as an instance of the enumeration
* class <code>java.nio.ByteOrder</code>, where
* <code>ByteOrder.BIG_ENDIAN</code> indicates network byte order
* and <code>ByteOrder.LITTLE_ENDIAN</code> indicates the reverse
* order. By default, the value is
* <code>ByteOrder.BIG_ENDIAN</code>.
*/
protected ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
/** {@collect.stats}
* The current read position within the stream. Subclasses are
* responsible for keeping this value current from any method they
* override that alters the read position.
*/
protected long streamPos;
/** {@collect.stats}
* The current bit offset within the stream. Subclasses are
* responsible for keeping this value current from any method they
* override that alters the bit offset.
*/
protected int bitOffset;
/** {@collect.stats}
* The position prior to which data may be discarded. Seeking
* to a smaller position is not allowed. <code>flushedPos</code>
* will always be >= 0.
*/
protected long flushedPos = 0;
/** {@collect.stats}
* Constructs an <code>ImageInputStreamImpl</code>.
*/
public ImageInputStreamImpl() {
}
/** {@collect.stats}
* Throws an <code>IOException</code> if the stream has been closed.
* Subclasses may call this method from any of their methods that
* require the stream not to be closed.
*
* @exception IOException if the stream is closed.
*/
protected final void checkClosed() throws IOException {
if (isClosed) {
throw new IOException("closed");
}
}
public void setByteOrder(ByteOrder byteOrder) {
this.byteOrder = byteOrder;
}
public ByteOrder getByteOrder() {
return byteOrder;
}
/** {@collect.stats}
* Reads a single byte from the stream and returns it as an
* <code>int</code> between 0 and 255. If EOF is reached,
* <code>-1</code> is returned.
*
* <p> Subclasses must provide an implementation for this method.
* The subclass implementation should update the stream position
* before exiting.
*
* <p> The bit offset within the stream must be reset to zero before
* the read occurs.
*
* @return the value of the next byte in the stream, or <code>-1</code>
* if EOF is reached.
*
* @exception IOException if the stream has been closed.
*/
public abstract int read() throws IOException;
/** {@collect.stats}
* A convenience method that calls <code>read(b, 0, b.length)</code>.
*
* <p> The bit offset within the stream is reset to zero before
* the read occurs.
*
* @return the number of bytes actually read, or <code>-1</code>
* to indicate EOF.
*
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/** {@collect.stats}
* Reads up to <code>len</code> bytes from the stream, and stores
* them into <code>b</code> starting at index <code>off</code>.
* If no bytes can be read because the end of the stream has been
* reached, <code>-1</code> is returned.
*
* <p> The bit offset within the stream must be reset to zero before
* the read occurs.
*
* <p> Subclasses must provide an implementation for this method.
* The subclass implementation should update the stream position
* before exiting.
*
* @param b an array of bytes to be written to.
* @param off the starting position within <code>b</code> to write to.
* @param len the maximum number of bytes to read.
*
* @return the number of bytes actually read, or <code>-1</code>
* to indicate EOF.
*
* @exception IndexOutOfBoundsException if <code>off</code> is
* negative, <code>len</code> is negative, or <code>off +
* len</code> is greater than <code>b.length</code>.
* @exception NullPointerException if <code>b</code> is
* <code>null</code>.
* @exception IOException if an I/O error occurs.
*/
public abstract int read(byte[] b, int off, int len) throws IOException;
public void readBytes(IIOByteBuffer buf, int len) throws IOException {
if (len < 0) {
throw new IndexOutOfBoundsException("len < 0!");
}
if (buf == null) {
throw new NullPointerException("buf == null!");
}
byte[] data = new byte[len];
len = read(data, 0, len);
buf.setData(data);
buf.setOffset(0);
buf.setLength(len);
}
public boolean readBoolean() throws IOException {
int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return (ch != 0);
}
public byte readByte() throws IOException {
int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return (byte)ch;
}
public int readUnsignedByte() throws IOException {
int ch = this.read();
if (ch < 0) {
throw new EOFException();
}
return ch;
}
public short readShort() throws IOException {
if (read(byteBuf, 0, 2) < 0) {
throw new EOFException();
}
if (byteOrder == ByteOrder.BIG_ENDIAN) {
return (short)
(((byteBuf[0] & 0xff) << 8) | ((byteBuf[1] & 0xff) << 0));
} else {
return (short)
(((byteBuf[1] & 0xff) << 8) | ((byteBuf[0] & 0xff) << 0));
}
}
public int readUnsignedShort() throws IOException {
return ((int)readShort()) & 0xffff;
}
public char readChar() throws IOException {
return (char)readShort();
}
public int readInt() throws IOException {
if (read(byteBuf, 0, 4) < 0) {
throw new EOFException();
}
if (byteOrder == ByteOrder.BIG_ENDIAN) {
return
(((byteBuf[0] & 0xff) << 24) | ((byteBuf[1] & 0xff) << 16) |
((byteBuf[2] & 0xff) << 8) | ((byteBuf[3] & 0xff) << 0));
} else {
return
(((byteBuf[3] & 0xff) << 24) | ((byteBuf[2] & 0xff) << 16) |
((byteBuf[1] & 0xff) << 8) | ((byteBuf[0] & 0xff) << 0));
}
}
public long readUnsignedInt() throws IOException {
return ((long)readInt()) & 0xffffffffL;
}
public long readLong() throws IOException {
// REMIND: Once 6277756 is fixed, we should do a bulk read of all 8
// bytes here as we do in readShort() and readInt() for even better
// performance (see 6347575 for details).
int i1 = readInt();
int i2 = readInt();
if (byteOrder == ByteOrder.BIG_ENDIAN) {
return ((long)i1 << 32) + (i2 & 0xFFFFFFFFL);
} else {
return ((long)i2 << 32) + (i1 & 0xFFFFFFFFL);
}
}
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
public String readLine() throws IOException {
StringBuffer input = new StringBuffer();
int c = -1;
boolean eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = getStreamPosition();
if ((read()) != '\n') {
seek(cur);
}
break;
default:
input.append((char)c);
break;
}
}
if ((c == -1) && (input.length() == 0)) {
return null;
}
return input.toString();
}
public String readUTF() throws IOException {
this.bitOffset = 0;
// Fix 4494369: method ImageInputStreamImpl.readUTF()
// does not work as specified (it should always assume
// network byte order).
ByteOrder oldByteOrder = getByteOrder();
setByteOrder(ByteOrder.BIG_ENDIAN);
String ret;
try {
ret = DataInputStream.readUTF(this);
} catch (IOException e) {
// Restore the old byte order even if an exception occurs
setByteOrder(oldByteOrder);
throw e;
}
setByteOrder(oldByteOrder);
return ret;
}
public void readFully(byte[] b, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > b.length!");
}
while (len > 0) {
int nbytes = read(b, off, len);
if (nbytes == -1) {
throw new EOFException();
}
off += nbytes;
len -= nbytes;
}
}
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length);
}
public void readFully(short[] s, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > s.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > s.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/2);
readFully(byteBuf, 0, nelts*2);
toShorts(byteBuf, s, off, nelts);
off += nelts;
len -= nelts;
}
}
public void readFully(char[] c, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > c.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > c.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/2);
readFully(byteBuf, 0, nelts*2);
toChars(byteBuf, c, off, nelts);
off += nelts;
len -= nelts;
}
}
public void readFully(int[] i, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > i.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > i.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/4);
readFully(byteBuf, 0, nelts*4);
toInts(byteBuf, i, off, nelts);
off += nelts;
len -= nelts;
}
}
public void readFully(long[] l, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > l.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > l.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/8);
readFully(byteBuf, 0, nelts*8);
toLongs(byteBuf, l, off, nelts);
off += nelts;
len -= nelts;
}
}
public void readFully(float[] f, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > f.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > f.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/4);
readFully(byteBuf, 0, nelts*4);
toFloats(byteBuf, f, off, nelts);
off += nelts;
len -= nelts;
}
}
public void readFully(double[] d, int off, int len) throws IOException {
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > d.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off + len > d.length!");
}
while (len > 0) {
int nelts = Math.min(len, byteBuf.length/8);
readFully(byteBuf, 0, nelts*8);
toDoubles(byteBuf, d, off, nelts);
off += nelts;
len -= nelts;
}
}
private void toShorts(byte[] b, short[] s, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
s[off + j] = (short)((b0 << 8) | b1);
boff += 2;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 1];
int b1 = b[boff] & 0xff;
s[off + j] = (short)((b0 << 8) | b1);
boff += 2;
}
}
}
private void toChars(byte[] b, char[] c, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
c[off + j] = (char)((b0 << 8) | b1);
boff += 2;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 1];
int b1 = b[boff] & 0xff;
c[off + j] = (char)((b0 << 8) | b1);
boff += 2;
}
}
}
private void toInts(byte[] b, int[] i, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
int b2 = b[boff + 2] & 0xff;
int b3 = b[boff + 3] & 0xff;
i[off + j] = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
boff += 4;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 3];
int b1 = b[boff + 2] & 0xff;
int b2 = b[boff + 1] & 0xff;
int b3 = b[boff] & 0xff;
i[off + j] = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
boff += 4;
}
}
}
private void toLongs(byte[] b, long[] l, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
int b2 = b[boff + 2] & 0xff;
int b3 = b[boff + 3] & 0xff;
int b4 = b[boff + 4];
int b5 = b[boff + 5] & 0xff;
int b6 = b[boff + 6] & 0xff;
int b7 = b[boff + 7] & 0xff;
int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7;
l[off + j] = ((long)i0 << 32) | (i1 & 0xffffffffL);
boff += 8;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 7];
int b1 = b[boff + 6] & 0xff;
int b2 = b[boff + 5] & 0xff;
int b3 = b[boff + 4] & 0xff;
int b4 = b[boff + 3];
int b5 = b[boff + 2] & 0xff;
int b6 = b[boff + 1] & 0xff;
int b7 = b[boff] & 0xff;
int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7;
l[off + j] = ((long)i0 << 32) | (i1 & 0xffffffffL);
boff += 8;
}
}
}
private void toFloats(byte[] b, float[] f, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
int b2 = b[boff + 2] & 0xff;
int b3 = b[boff + 3] & 0xff;
int i = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
f[off + j] = Float.intBitsToFloat(i);
boff += 4;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 3];
int b1 = b[boff + 2] & 0xff;
int b2 = b[boff + 1] & 0xff;
int b3 = b[boff + 0] & 0xff;
int i = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
f[off + j] = Float.intBitsToFloat(i);
boff += 4;
}
}
}
private void toDoubles(byte[] b, double[] d, int off, int len) {
int boff = 0;
if (byteOrder == ByteOrder.BIG_ENDIAN) {
for (int j = 0; j < len; j++) {
int b0 = b[boff];
int b1 = b[boff + 1] & 0xff;
int b2 = b[boff + 2] & 0xff;
int b3 = b[boff + 3] & 0xff;
int b4 = b[boff + 4];
int b5 = b[boff + 5] & 0xff;
int b6 = b[boff + 6] & 0xff;
int b7 = b[boff + 7] & 0xff;
int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7;
long l = ((long)i0 << 32) | (i1 & 0xffffffffL);
d[off + j] = Double.longBitsToDouble(l);
boff += 8;
}
} else {
for (int j = 0; j < len; j++) {
int b0 = b[boff + 7];
int b1 = b[boff + 6] & 0xff;
int b2 = b[boff + 5] & 0xff;
int b3 = b[boff + 4] & 0xff;
int b4 = b[boff + 3];
int b5 = b[boff + 2] & 0xff;
int b6 = b[boff + 1] & 0xff;
int b7 = b[boff] & 0xff;
int i0 = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
int i1 = (b4 << 24) | (b5 << 16) | (b6 << 8) | b7;
long l = ((long)i0 << 32) | (i1 & 0xffffffffL);
d[off + j] = Double.longBitsToDouble(l);
boff += 8;
}
}
}
public long getStreamPosition() throws IOException {
checkClosed();
return streamPos;
}
public int getBitOffset() throws IOException {
checkClosed();
return bitOffset;
}
public void setBitOffset(int bitOffset) throws IOException {
checkClosed();
if (bitOffset < 0 || bitOffset > 7) {
throw new IllegalArgumentException("bitOffset must be betwwen 0 and 7!");
}
this.bitOffset = bitOffset;
}
public int readBit() throws IOException {
checkClosed();
// Compute final bit offset before we call read() and seek()
int newBitOffset = (this.bitOffset + 1) & 0x7;
int val = read();
if (val == -1) {
throw new EOFException();
}
if (newBitOffset != 0) {
// Move byte position back if in the middle of a byte
seek(getStreamPosition() - 1);
// Shift the bit to be read to the rightmost position
val >>= 8 - newBitOffset;
}
this.bitOffset = newBitOffset;
return val & 0x1;
}
public long readBits(int numBits) throws IOException {
checkClosed();
if (numBits < 0 || numBits > 64) {
throw new IllegalArgumentException();
}
if (numBits == 0) {
return 0L;
}
// Have to read additional bits on the left equal to the bit offset
int bitsToRead = numBits + bitOffset;
// Compute final bit offset before we call read() and seek()
int newBitOffset = (this.bitOffset + numBits) & 0x7;
// Read a byte at a time, accumulate
long accum = 0L;
while (bitsToRead > 0) {
int val = read();
if (val == -1) {
throw new EOFException();
}
accum <<= 8;
accum |= val;
bitsToRead -= 8;
}
// Move byte position back if in the middle of a byte
if (newBitOffset != 0) {
seek(getStreamPosition() - 1);
}
this.bitOffset = newBitOffset;
// Shift away unwanted bits on the right.
accum >>>= (-bitsToRead); // Negative of bitsToRead == extra bits read
// Mask out unwanted bits on the left
accum &= (-1L >>> (64 - numBits));
return accum;
}
/** {@collect.stats}
* Returns <code>-1L</code> to indicate that the stream has unknown
* length. Subclasses must override this method to provide actual
* length information.
*
* @return -1L to indicate unknown length.
*/
public long length() {
return -1L;
}
/** {@collect.stats}
* Advances the current stream position by calling
* <code>seek(getStreamPosition() + n)</code>.
*
* <p> The bit offset is reset to zero.
*
* @param n the number of bytes to seek forward.
*
* @return an <code>int</code> representing the number of bytes
* skipped.
*
* @exception IOException if <code>getStreamPosition</code>
* throws an <code>IOException</code> when computing either
* the starting or ending position.
*/
public int skipBytes(int n) throws IOException {
long pos = getStreamPosition();
seek(pos + n);
return (int)(getStreamPosition() - pos);
}
/** {@collect.stats}
* Advances the current stream position by calling
* <code>seek(getStreamPosition() + n)</code>.
*
* <p> The bit offset is reset to zero.
*
* @param n the number of bytes to seek forward.
*
* @return a <code>long</code> representing the number of bytes
* skipped.
*
* @exception IOException if <code>getStreamPosition</code>
* throws an <code>IOException</code> when computing either
* the starting or ending position.
*/
public long skipBytes(long n) throws IOException {
long pos = getStreamPosition();
seek(pos + n);
return getStreamPosition() - pos;
}
public void seek(long pos) throws IOException {
checkClosed();
// This test also covers pos < 0
if (pos < flushedPos) {
throw new IndexOutOfBoundsException("pos < flushedPos!");
}
this.streamPos = pos;
this.bitOffset = 0;
}
/** {@collect.stats}
* Pushes the current stream position onto a stack of marked
* positions.
*/
public void mark() {
try {
markByteStack.push(new Long(getStreamPosition()));
markBitStack.push(new Integer(getBitOffset()));
} catch (IOException e) {
}
}
/** {@collect.stats}
* Resets the current stream byte and bit positions from the stack
* of marked positions.
*
* <p> An <code>IOException</code> will be thrown if the previous
* marked position lies in the discarded portion of the stream.
*
* @exception IOException if an I/O error occurs.
*/
public void reset() throws IOException {
if (markByteStack.empty()) {
return;
}
long pos = ((Long)markByteStack.pop()).longValue();
if (pos < flushedPos) {
throw new IIOException
("Previous marked position has been discarded!");
}
seek(pos);
int offset = ((Integer)markBitStack.pop()).intValue();
setBitOffset(offset);
}
public void flushBefore(long pos) throws IOException {
checkClosed();
if (pos < flushedPos) {
throw new IndexOutOfBoundsException("pos < flushedPos!");
}
if (pos > getStreamPosition()) {
throw new IndexOutOfBoundsException("pos > getStreamPosition()!");
}
// Invariant: flushedPos >= 0
flushedPos = pos;
}
public void flush() throws IOException {
flushBefore(getStreamPosition());
}
public long getFlushedPosition() {
return flushedPos;
}
/** {@collect.stats}
* Default implementation returns false. Subclasses should
* override this if they cache data.
*/
public boolean isCached() {
return false;
}
/** {@collect.stats}
* Default implementation returns false. Subclasses should
* override this if they cache data in main memory.
*/
public boolean isCachedMemory() {
return false;
}
/** {@collect.stats}
* Default implementation returns false. Subclasses should
* override this if they cache data in a temporary file.
*/
public boolean isCachedFile() {
return false;
}
public void close() throws IOException {
checkClosed();
isClosed = true;
}
/** {@collect.stats}
* Finalizes this object prior to garbage collection. The
* <code>close</code> method is called to close any open input
* source. This method should not be called from application
* code.
*
* @exception Throwable if an error occurs during superclass
* finalization.
*/
protected void finalize() throws Throwable {
if (!isClosed) {
try {
close();
} catch (IOException e) {
}
}
super.finalize();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.sun.imageio.stream.StreamCloser;
import com.sun.imageio.stream.StreamFinalizer;
import sun.java2d.Disposer;
import sun.java2d.DisposerRecord;
/** {@collect.stats}
* An implementation of <code>ImageInputStream</code> that gets its
* input from a regular <code>InputStream</code>. A file is used to
* cache previously read data.
*
*/
public class FileCacheImageInputStream extends ImageInputStreamImpl {
private InputStream stream;
private File cacheFile;
private RandomAccessFile cache;
private static final int BUFFER_LENGTH = 1024;
private byte[] buf = new byte[BUFFER_LENGTH];
private long length = 0L;
private boolean foundEOF = false;
/** {@collect.stats} The referent to be registered with the Disposer. */
private final Object disposerReferent;
/** {@collect.stats} The DisposerRecord that closes the underlying cache. */
private final DisposerRecord disposerRecord;
/** {@collect.stats} The CloseAction that closes the stream in
* the StreamCloser's shutdown hook */
private final StreamCloser.CloseAction closeAction;
/** {@collect.stats}
* Constructs a <code>FileCacheImageInputStream</code> that will read
* from a given <code>InputStream</code>.
*
* <p> A temporary file is used as a cache. If
* <code>cacheDir</code>is non-<code>null</code> and is a
* directory, the file will be created there. If it is
* <code>null</code>, the system-dependent default temporary-file
* directory will be used (see the documentation for
* <code>File.createTempFile</code> for details).
*
* @param stream an <code>InputStream</code> to read from.
* @param cacheDir a <code>File</code> indicating where the
* cache file should be created, or <code>null</code> to use the
* system directory.
*
* @exception IllegalArgumentException if <code>stream</code> is
* <code>null</code>.
* @exception IllegalArgumentException if <code>cacheDir</code> is
* non-<code>null</code> but is not a directory.
* @exception IOException if a cache file cannot be created.
*/
public FileCacheImageInputStream(InputStream stream, File cacheDir)
throws IOException {
if (stream == null) {
throw new IllegalArgumentException("stream == null!");
}
if ((cacheDir != null) && !(cacheDir.isDirectory())) {
throw new IllegalArgumentException("Not a directory!");
}
this.stream = stream;
this.cacheFile =
File.createTempFile("imageio", ".tmp", cacheDir);
this.cache = new RandomAccessFile(cacheFile, "rw");
this.closeAction = StreamCloser.createCloseAction(this);
StreamCloser.addToQueue(closeAction);
disposerRecord = new StreamDisposerRecord(cacheFile, cache);
if (getClass() == FileCacheImageInputStream.class) {
disposerReferent = new Object();
Disposer.addRecord(disposerReferent, disposerRecord);
} else {
disposerReferent = new StreamFinalizer(this);
}
}
/** {@collect.stats}
* Ensures that at least <code>pos</code> bytes are cached,
* or the end of the source is reached. The return value
* is equal to the smaller of <code>pos</code> and the
* length of the source file.
*/
private long readUntil(long pos) throws IOException {
// We've already got enough data cached
if (pos < length) {
return pos;
}
// pos >= length but length isn't getting any bigger, so return it
if (foundEOF) {
return length;
}
long len = pos - length;
cache.seek(length);
while (len > 0) {
// Copy a buffer's worth of data from the source to the cache
// BUFFER_LENGTH will always fit into an int so this is safe
int nbytes =
stream.read(buf, 0, (int)Math.min(len, (long)BUFFER_LENGTH));
if (nbytes == -1) {
foundEOF = true;
return length;
}
cache.write(buf, 0, nbytes);
len -= nbytes;
length += nbytes;
}
return pos;
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
long next = streamPos + 1;
long pos = readUntil(next);
if (pos >= next) {
cache.seek(streamPos++);
return cache.read();
} else {
return -1;
}
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
if (b == null) {
throw new NullPointerException("b == null!");
}
// Fix 4430357 - if off + len < 0, overflow occurred
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off+len > b.length || off+len < 0!");
}
bitOffset = 0;
if (len == 0) {
return 0;
}
long pos = readUntil(streamPos + len);
// len will always fit into an int so this is safe
len = (int)Math.min((long)len, pos - streamPos);
if (len > 0) {
cache.seek(streamPos);
cache.readFully(b, off, len);
streamPos += len;
return len;
} else {
return -1;
}
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageInputStream</code> caches data in order to allow
* seeking backwards.
*
* @return <code>true</code>.
*
* @see #isCachedMemory
* @see #isCachedFile
*/
public boolean isCached() {
return true;
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageInputStream</code> maintains a file cache.
*
* @return <code>true</code>.
*
* @see #isCached
* @see #isCachedMemory
*/
public boolean isCachedFile() {
return true;
}
/** {@collect.stats}
* Returns <code>false</code> since this
* <code>ImageInputStream</code> does not maintain a main memory
* cache.
*
* @return <code>false</code>.
*
* @see #isCached
* @see #isCachedFile
*/
public boolean isCachedMemory() {
return false;
}
/** {@collect.stats}
* Closes this <code>FileCacheImageInputStream</code>, closing
* and removing the cache file. The source <code>InputStream</code>
* is not closed.
*
* @exception IOException if an error occurs.
*/
public void close() throws IOException {
super.close();
disposerRecord.dispose(); // this will close/delete the cache file
stream = null;
cache = null;
cacheFile = null;
StreamCloser.removeFromQueue(closeAction);
}
/** {@collect.stats}
* {@inheritDoc}
*/
protected void finalize() throws Throwable {
// Empty finalizer: for performance reasons we instead use the
// Disposer mechanism for ensuring that the underlying
// RandomAccessFile is closed/deleted prior to garbage collection
}
private static class StreamDisposerRecord implements DisposerRecord {
private File cacheFile;
private RandomAccessFile cache;
public StreamDisposerRecord(File cacheFile, RandomAccessFile cache) {
this.cacheFile = cacheFile;
this.cache = cache;
}
public synchronized void dispose() {
if (cache != null) {
try {
cache.close();
} catch (IOException e) {
} finally {
cache = null;
}
}
if (cacheFile != null) {
cacheFile.delete();
cacheFile = null;
}
// Note: Explicit removal of the stream from the StreamCloser
// queue is not mandatory in this case, as it will be removed
// automatically by GC shortly after this method is called.
}
}
}
|
Java
|
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio.stream;
import java.io.IOException;
import java.io.OutputStream;
/** {@collect.stats}
* An implementation of <code>ImageOutputStream</code> that writes its
* output to a regular <code>OutputStream</code>. A memory buffer is
* used to cache at least the data between the discard position and
* the current write position. The only constructor takes an
* <code>OutputStream</code>, so this class may not be used for
* read/modify/write operations. Reading can occur only on parts of
* the stream that have already been written to the cache and not
* yet flushed.
*
*/
public class MemoryCacheImageOutputStream extends ImageOutputStreamImpl {
private OutputStream stream;
private MemoryCache cache = new MemoryCache();
/** {@collect.stats}
* Constructs a <code>MemoryCacheImageOutputStream</code> that will write
* to a given <code>OutputStream</code>.
*
* @param stream an <code>OutputStream</code> to write to.
*
* @exception IllegalArgumentException if <code>stream</code> is
* <code>null</code>.
*/
public MemoryCacheImageOutputStream(OutputStream stream) {
if (stream == null) {
throw new IllegalArgumentException("stream == null!");
}
this.stream = stream;
}
public int read() throws IOException {
checkClosed();
bitOffset = 0;
int val = cache.read(streamPos);
if (val != -1) {
++streamPos;
}
return val;
}
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
if (b == null) {
throw new NullPointerException("b == null!");
}
// Fix 4467608: read([B,I,I) works incorrectly if len<=0
if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
throw new IndexOutOfBoundsException
("off < 0 || len < 0 || off+len > b.length || off+len < 0!");
}
bitOffset = 0;
if (len == 0) {
return 0;
}
// check if we're already at/past EOF i.e.
// no more bytes left to read from cache
long bytesLeftInCache = cache.getLength() - streamPos;
if (bytesLeftInCache <= 0) {
return -1; // EOF
}
// guaranteed by now that bytesLeftInCache > 0 && len > 0
// and so the rest of the error checking is done by cache.read()
// NOTE that alot of error checking is duplicated
len = (int)Math.min(bytesLeftInCache, (long)len);
cache.read(b, off, len, streamPos);
streamPos += len;
return len;
}
public void write(int b) throws IOException {
flushBits(); // this will call checkClosed() for us
cache.write(b, streamPos);
++streamPos;
}
public void write(byte[] b, int off, int len) throws IOException {
flushBits(); // this will call checkClosed() for us
cache.write(b, off, len, streamPos);
streamPos += len;
}
public long length() {
try {
checkClosed();
return cache.getLength();
} catch (IOException e) {
return -1L;
}
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageOutputStream</code> caches data in order to allow
* seeking backwards.
*
* @return <code>true</code>.
*
* @see #isCachedMemory
* @see #isCachedFile
*/
public boolean isCached() {
return true;
}
/** {@collect.stats}
* Returns <code>false</code> since this
* <code>ImageOutputStream</code> does not maintain a file cache.
*
* @return <code>false</code>.
*
* @see #isCached
* @see #isCachedMemory
*/
public boolean isCachedFile() {
return false;
}
/** {@collect.stats}
* Returns <code>true</code> since this
* <code>ImageOutputStream</code> maintains a main memory cache.
*
* @return <code>true</code>.
*
* @see #isCached
* @see #isCachedFile
*/
public boolean isCachedMemory() {
return true;
}
/** {@collect.stats}
* Closes this <code>MemoryCacheImageOutputStream</code>. All
* pending data is flushed to the output, and the cache
* is released. The destination <code>OutputStream</code>
* is not closed.
*/
public void close() throws IOException {
long length = cache.getLength();
seek(length);
flushBefore(length);
super.close();
cache.reset();
cache = null;
stream = null;
}
public void flushBefore(long pos) throws IOException {
long oFlushedPos = flushedPos;
super.flushBefore(pos); // this will call checkClosed() for us
long flushBytes = flushedPos - oFlushedPos;
cache.writeToStream(stream, oFlushedPos, flushBytes);
cache.disposeBefore(flushedPos);
stream.flush();
}
}
|
Java
|
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.spi.ImageReaderWriterSpi;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.spi.ImageInputStreamSpi;
import javax.imageio.spi.ImageOutputStreamSpi;
import javax.imageio.spi.ImageTranscoderSpi;
import javax.imageio.spi.ServiceRegistry;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import sun.awt.AppContext;
import sun.security.action.GetPropertyAction;
/** {@collect.stats}
* A class containing static convenience methods for locating
* <code>ImageReader</code>s and <code>ImageWriter</code>s, and
* performing simple encoding and decoding.
*
*/
public final class ImageIO {
private static final IIORegistry theRegistry =
IIORegistry.getDefaultInstance();
/** {@collect.stats}
* Constructor is private to prevent instantiation.
*/
private ImageIO() {}
/** {@collect.stats}
* Scans for plug-ins on the application class path,
* loads their service provider classes, and registers a service
* provider instance for each one found with the
* <code>IIORegistry</code>.
*
* <p>This method is needed because the application class path can
* theoretically change, or additional plug-ins may become available.
* Rather than re-scanning the classpath on every invocation of the
* API, the class path is scanned automatically only on the first
* invocation. Clients can call this method to prompt a re-scan.
* Thus this method need only be invoked by sophisticated applications
* which dynamically make new plug-ins available at runtime.
*
* <p> The <code>getResources</code> method of the context
* <code>ClassLoader</code> is used locate JAR files containing
* files named
* <code>META-INF/services/javax.imageio.spi.</code><i>classname</i>,
* where <i>classname</i> is one of <code>ImageReaderSpi</code>,
* <code>ImageWriterSpi</code>, <code>ImageTranscoderSpi</code>,
* <code>ImageInputStreamSpi</code>, or
* <code>ImageOutputStreamSpi</code>, along the application class
* path.
*
* <p> The contents of the located files indicate the names of
* actual implementation classes which implement the
* aforementioned service provider interfaces; the default class
* loader is then used to load each of these classes and to
* instantiate an instance of each class, which is then placed
* into the registry for later retrieval.
*
* <p> The exact set of locations searched depends on the
* implementation of the Java runtime enviroment.
*
* @see ClassLoader#getResources
*/
public static void scanForPlugins() {
theRegistry.registerApplicationClasspathSpis();
}
// ImageInputStreams
/** {@collect.stats}
* A class to hold information about caching. Each
* <code>ThreadGroup</code> will have its own copy
* via the <code>AppContext</code> mechanism.
*/
static class CacheInfo {
boolean useCache = true;
File cacheDirectory = null;
Boolean hasPermission = null;
public CacheInfo() {}
public boolean getUseCache() {
return useCache;
}
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
public File getCacheDirectory() {
return cacheDirectory;
}
public void setCacheDirectory(File cacheDirectory) {
this.cacheDirectory = cacheDirectory;
}
public Boolean getHasPermission() {
return hasPermission;
}
public void setHasPermission(Boolean hasPermission) {
this.hasPermission = hasPermission;
}
}
/** {@collect.stats}
* Returns the <code>CacheInfo</code> object associated with this
* <code>ThreadGroup</code>.
*/
private static synchronized CacheInfo getCacheInfo() {
AppContext context = AppContext.getAppContext();
CacheInfo info = (CacheInfo)context.get(CacheInfo.class);
if (info == null) {
info = new CacheInfo();
context.put(CacheInfo.class, info);
}
return info;
}
/** {@collect.stats}
* Returns the default temporary (cache) directory as defined by the
* java.io.tmpdir system property.
*/
private static String getTempDir() {
GetPropertyAction a = new GetPropertyAction("java.io.tmpdir");
return (String)AccessController.doPrivileged(a);
}
/** {@collect.stats}
* Determines whether the caller has write access to the cache
* directory, stores the result in the <code>CacheInfo</code> object,
* and returns the decision. This method helps to prevent mysterious
* SecurityExceptions to be thrown when this convenience class is used
* in an applet, for example.
*/
private static boolean hasCachePermission() {
Boolean hasPermission = getCacheInfo().getHasPermission();
if (hasPermission != null) {
return hasPermission.booleanValue();
} else {
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
File cachedir = getCacheDirectory();
String cachepath;
if (cachedir != null) {
cachepath = cachedir.getPath();
} else {
cachepath = getTempDir();
if (cachepath == null) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
}
security.checkWrite(cachepath);
}
} catch (SecurityException e) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
getCacheInfo().setHasPermission(Boolean.TRUE);
return true;
}
}
/** {@collect.stats}
* Sets a flag indicating whether a disk-based cache file should
* be used when creating <code>ImageInputStream</code>s and
* <code>ImageOutputStream</code>s.
*
* <p> When reading from a standard <code>InputStream</code>>, it
* may be necessary to save previously read information in a cache
* since the underlying stream does not allow data to be re-read.
* Similarly, when writing to a standard
* <code>OutputStream</code>, a cache may be used to allow a
* previously written value to be changed before flushing it to
* the final destination.
*
* <p> The cache may reside in main memory or on disk. Setting
* this flag to <code>false</code> disallows the use of disk for
* future streams, which may be advantageous when working with
* small images, as the overhead of creating and destroying files
* is removed.
*
* <p> On startup, the value is set to <code>true</code>.
*
* @param useCache a <code>boolean</code> indicating whether a
* cache file should be used, in cases where it is optional.
*
* @see #getUseCache
*/
public static void setUseCache(boolean useCache) {
getCacheInfo().setUseCache(useCache);
}
/** {@collect.stats}
* Returns the current value set by <code>setUseCache</code>, or
* <code>true</code> if no explicit setting has been made.
*
* @return true if a disk-based cache may be used for
* <code>ImageInputStream</code>s and
* <code>ImageOutputStream</code>s.
*
* @see #setUseCache
*/
public static boolean getUseCache() {
return getCacheInfo().getUseCache();
}
/** {@collect.stats}
* Sets the directory where cache files are to be created. A
* value of <code>null</code> indicates that the system-dependent
* default temporary-file directory is to be used. If
* <code>getUseCache</code> returns false, this value is ignored.
*
* @param cacheDirectory a <code>File</code> specifying a directory.
*
* @see File#createTempFile(String, String, File)
*
* @exception SecurityException if the security manager denies
* access to the directory.
* @exception IllegalArgumentException if <code>cacheDir</code> is
* non-<code>null</code> but is not a directory.
*
* @see #getCacheDirectory
*/
public static void setCacheDirectory(File cacheDirectory) {
if ((cacheDirectory != null) && !(cacheDirectory.isDirectory())) {
throw new IllegalArgumentException("Not a directory!");
}
getCacheInfo().setCacheDirectory(cacheDirectory);
getCacheInfo().setHasPermission(null);
}
/** {@collect.stats}
* Returns the current value set by
* <code>setCacheDirectory</code>, or <code>null</code> if no
* explicit setting has been made.
*
* @return a <code>File</code> indicating the directory where
* cache files will be created, or <code>null</code> to indicate
* the system-dependent default temporary-file directory.
*
* @see #setCacheDirectory
*/
public static File getCacheDirectory() {
return getCacheInfo().getCacheDirectory();
}
/** {@collect.stats}
* Returns an <code>ImageInputStream</code> that will take its
* input from the given <code>Object</code>. The set of
* <code>ImageInputStreamSpi</code>s registered with the
* <code>IIORegistry</code> class is queried and the first one
* that is able to take input from the supplied object is used to
* create the returned <code>ImageInputStream</code>. If no
* suitable <code>ImageInputStreamSpi</code> exists,
* <code>null</code> is returned.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching.
*
* @param input an <code>Object</code> to be used as an input
* source, such as a <code>File</code>, readable
* <code>RandomAccessFile</code>, or <code>InputStream</code>.
*
* @return an <code>ImageInputStream</code>, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>input</code>
* is <code>null</code>.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see javax.imageio.spi.ImageInputStreamSpi
*/
public static ImageInputStream createImageInputStream(Object input)
throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageInputStreamSpi.class,
true);
} catch (IllegalArgumentException e) {
return null;
}
boolean usecache = getUseCache() && hasCachePermission();
while (iter.hasNext()) {
ImageInputStreamSpi spi = (ImageInputStreamSpi)iter.next();
if (spi.getInputClass().isInstance(input)) {
try {
return spi.createInputStreamInstance(input,
usecache,
getCacheDirectory());
} catch (IOException e) {
throw new IIOException("Can't create cache file!", e);
}
}
}
return null;
}
// ImageOutputStreams
/** {@collect.stats}
* Returns an <code>ImageOutputStream</code> that will send its
* output to the given <code>Object</code>. The set of
* <code>ImageOutputStreamSpi</code>s registered with the
* <code>IIORegistry</code> class is queried and the first one
* that is able to send output from the supplied object is used to
* create the returned <code>ImageOutputStream</code>. If no
* suitable <code>ImageOutputStreamSpi</code> exists,
* <code>null</code> is returned.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching.
*
* @param output an <code>Object</code> to be used as an output
* destination, such as a <code>File</code>, writable
* <code>RandomAccessFile</code>, or <code>OutputStream</code>.
*
* @return an <code>ImageOutputStream</code>, or
* <code>null</code>.
*
* @exception IllegalArgumentException if <code>output</code> is
* <code>null</code>.
* @exception IOException if a cache file is needed but cannot be
* created.
*
* @see javax.imageio.spi.ImageOutputStreamSpi
*/
public static ImageOutputStream createImageOutputStream(Object output)
throws IOException {
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageOutputStreamSpi.class,
true);
} catch (IllegalArgumentException e) {
return null;
}
boolean usecache = getUseCache() && hasCachePermission();
while (iter.hasNext()) {
ImageOutputStreamSpi spi = (ImageOutputStreamSpi)iter.next();
if (spi.getOutputClass().isInstance(output)) {
try {
return spi.createOutputStreamInstance(output,
usecache,
getCacheDirectory());
} catch (IOException e) {
throw new IIOException("Can't create cache file!", e);
}
}
}
return null;
}
private static enum SpiInfo {
FORMAT_NAMES {
@Override
String[] info(ImageReaderWriterSpi spi) {
return spi.getFormatNames();
}
},
MIME_TYPES {
@Override
String[] info(ImageReaderWriterSpi spi) {
return spi.getMIMETypes();
}
},
FILE_SUFFIXES {
@Override
String[] info(ImageReaderWriterSpi spi) {
return spi.getFileSuffixes();
}
};
abstract String[] info(ImageReaderWriterSpi spi);
}
private static <S extends ImageReaderWriterSpi>
String[] getReaderWriterInfo(Class<S> spiClass, SpiInfo spiInfo)
{
// Ensure category is present
Iterator<S> iter;
try {
iter = theRegistry.getServiceProviders(spiClass, true);
} catch (IllegalArgumentException e) {
return new String[0];
}
HashSet<String> s = new HashSet<String>();
while (iter.hasNext()) {
ImageReaderWriterSpi spi = iter.next();
Collections.addAll(s, spiInfo.info(spi));
}
return s.toArray(new String[s.size()]);
}
// Readers
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* informal format names understood by the current set of registered
* readers.
*
* @return an array of <code>String</code>s.
*/
public static String[] getReaderFormatNames() {
return getReaderWriterInfo(ImageReaderSpi.class,
SpiInfo.FORMAT_NAMES);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* MIME types understood by the current set of registered
* readers.
*
* @return an array of <code>String</code>s.
*/
public static String[] getReaderMIMETypes() {
return getReaderWriterInfo(ImageReaderSpi.class,
SpiInfo.MIME_TYPES);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* file suffixes associated with the formats understood
* by the current set of registered readers.
*
* @return an array of <code>String</code>s.
* @since 1.6
*/
public static String[] getReaderFileSuffixes() {
return getReaderWriterInfo(ImageReaderSpi.class,
SpiInfo.FILE_SUFFIXES);
}
static class ImageReaderIterator implements Iterator<ImageReader> {
// Contains ImageReaderSpis
public Iterator iter;
public ImageReaderIterator(Iterator iter) {
this.iter = iter;
}
public boolean hasNext() {
return iter.hasNext();
}
public ImageReader next() {
ImageReaderSpi spi = null;
try {
spi = (ImageReaderSpi)iter.next();
return spi.createReaderInstance();
} catch (IOException e) {
// Deregister the spi in this case, but only as
// an ImageReaderSpi
theRegistry.deregisterServiceProvider(spi, ImageReaderSpi.class);
}
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
static class CanDecodeInputFilter
implements ServiceRegistry.Filter {
Object input;
public CanDecodeInputFilter(Object input) {
this.input = input;
}
public boolean filter(Object elt) {
try {
ImageReaderSpi spi = (ImageReaderSpi)elt;
ImageInputStream stream = null;
if (input instanceof ImageInputStream) {
stream = (ImageInputStream)input;
}
// Perform mark/reset as a defensive measure
// even though plug-ins are supposed to take
// care of it.
boolean canDecode = false;
if (stream != null) {
stream.mark();
}
canDecode = spi.canDecodeInput(input);
if (stream != null) {
stream.reset();
}
return canDecode;
} catch (IOException e) {
return false;
}
}
}
static class CanEncodeImageAndFormatFilter
implements ServiceRegistry.Filter {
ImageTypeSpecifier type;
String formatName;
public CanEncodeImageAndFormatFilter(ImageTypeSpecifier type,
String formatName) {
this.type = type;
this.formatName = formatName;
}
public boolean filter(Object elt) {
ImageWriterSpi spi = (ImageWriterSpi)elt;
return Arrays.asList(spi.getFormatNames()).contains(formatName) &&
spi.canEncodeImage(type);
}
}
static class ContainsFilter
implements ServiceRegistry.Filter {
Method method;
String name;
// method returns an array of Strings
public ContainsFilter(Method method,
String name) {
this.method = method;
this.name = name;
}
public boolean filter(Object elt) {
try {
return contains((String[])method.invoke(elt), name);
} catch (Exception e) {
return false;
}
}
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageReader</code>s that claim to be able to
* decode the supplied <code>Object</code>, typically an
* <code>ImageInputStream</code>.
*
* <p> The stream position is left at its prior position upon
* exit from this method.
*
* @param input an <code>ImageInputStream</code> or other
* <code>Object</code> containing encoded image data.
*
* @return an <code>Iterator</code> containing <code>ImageReader</code>s.
*
* @exception IllegalArgumentException if <code>input</code> is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageReaderSpi#canDecodeInput
*/
public static Iterator<ImageReader> getImageReaders(Object input) {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
new CanDecodeInputFilter(input),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageReader>emptyList().iterator();
}
return new ImageReaderIterator(iter);
}
private static Method readerFormatNamesMethod;
private static Method readerFileSuffixesMethod;
private static Method readerMIMETypesMethod;
private static Method writerFormatNamesMethod;
private static Method writerFileSuffixesMethod;
private static Method writerMIMETypesMethod;
static {
try {
readerFormatNamesMethod =
ImageReaderSpi.class.getMethod("getFormatNames");
readerFileSuffixesMethod =
ImageReaderSpi.class.getMethod("getFileSuffixes");
readerMIMETypesMethod =
ImageReaderSpi.class.getMethod("getMIMETypes");
writerFormatNamesMethod =
ImageWriterSpi.class.getMethod("getFormatNames");
writerFileSuffixesMethod =
ImageWriterSpi.class.getMethod("getFileSuffixes");
writerMIMETypesMethod =
ImageWriterSpi.class.getMethod("getMIMETypes");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageReader</code>s that claim to be able to
* decode the named format.
*
* @param formatName a <code>String</code> containing the informal
* name of a format (<i>e.g.</i>, "jpeg" or "tiff".
*
* @return an <code>Iterator</code> containing
* <code>ImageReader</code>s.
*
* @exception IllegalArgumentException if <code>formatName</code>
* is <code>null</code>.
*
* @see javax.imageio.spi.ImageReaderSpi#getFormatNames
*/
public static Iterator<ImageReader>
getImageReadersByFormatName(String formatName)
{
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
new ContainsFilter(readerFormatNamesMethod,
formatName),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageReader>emptyList().iterator();
}
return new ImageReaderIterator(iter);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageReader</code>s that claim to be able to
* decode files with the given suffix.
*
* @param fileSuffix a <code>String</code> containing a file
* suffix (<i>e.g.</i>, "jpg" or "tiff").
*
* @return an <code>Iterator</code> containing
* <code>ImageReader</code>s.
*
* @exception IllegalArgumentException if <code>fileSuffix</code>
* is <code>null</code>.
*
* @see javax.imageio.spi.ImageReaderSpi#getFileSuffixes
*/
public static Iterator<ImageReader>
getImageReadersBySuffix(String fileSuffix)
{
if (fileSuffix == null) {
throw new IllegalArgumentException("fileSuffix == null!");
}
// Ensure category is present
Iterator iter;
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
new ContainsFilter(readerFileSuffixesMethod,
fileSuffix),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageReader>emptyList().iterator();
}
return new ImageReaderIterator(iter);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageReader</code>s that claim to be able to
* decode files with the given MIME type.
*
* @param MIMEType a <code>String</code> containing a file
* suffix (<i>e.g.</i>, "image/jpeg" or "image/x-bmp").
*
* @return an <code>Iterator</code> containing
* <code>ImageReader</code>s.
*
* @exception IllegalArgumentException if <code>MIMEType</code> is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageReaderSpi#getMIMETypes
*/
public static Iterator<ImageReader>
getImageReadersByMIMEType(String MIMEType)
{
if (MIMEType == null) {
throw new IllegalArgumentException("MIMEType == null!");
}
// Ensure category is present
Iterator iter;
try {
iter = theRegistry.getServiceProviders(ImageReaderSpi.class,
new ContainsFilter(readerMIMETypesMethod,
MIMEType),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageReader>emptyList().iterator();
}
return new ImageReaderIterator(iter);
}
// Writers
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* informal format names understood by the current set of registered
* writers.
*
* @return an array of <code>String</code>s.
*/
public static String[] getWriterFormatNames() {
return getReaderWriterInfo(ImageWriterSpi.class,
SpiInfo.FORMAT_NAMES);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* MIME types understood by the current set of registered
* writers.
*
* @return an array of <code>String</code>s.
*/
public static String[] getWriterMIMETypes() {
return getReaderWriterInfo(ImageWriterSpi.class,
SpiInfo.MIME_TYPES);
}
/** {@collect.stats}
* Returns an array of <code>String</code>s listing all of the
* file suffixes associated with the formats understood
* by the current set of registered writers.
*
* @return an array of <code>String</code>s.
* @since 1.6
*/
public static String[] getWriterFileSuffixes() {
return getReaderWriterInfo(ImageWriterSpi.class,
SpiInfo.FILE_SUFFIXES);
}
static class ImageWriterIterator implements Iterator<ImageWriter> {
// Contains ImageWriterSpis
public Iterator iter;
public ImageWriterIterator(Iterator iter) {
this.iter = iter;
}
public boolean hasNext() {
return iter.hasNext();
}
public ImageWriter next() {
ImageWriterSpi spi = null;
try {
spi = (ImageWriterSpi)iter.next();
return spi.createWriterInstance();
} catch (IOException e) {
// Deregister the spi in this case, but only as a writerSpi
theRegistry.deregisterServiceProvider(spi, ImageWriterSpi.class);
}
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private static boolean contains(String[] names, String name) {
for (int i = 0; i < names.length; i++) {
if (name.equalsIgnoreCase(names[i])) {
return true;
}
}
return false;
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageWriter</code>s that claim to be able to
* encode the named format.
*
* @param formatName a <code>String</code> containing the informal
* name of a format (<i>e.g.</i>, "jpeg" or "tiff".
*
* @return an <code>Iterator</code> containing
* <code>ImageWriter</code>s.
*
* @exception IllegalArgumentException if <code>formatName</code> is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageWriterSpi#getFormatNames
*/
public static Iterator<ImageWriter>
getImageWritersByFormatName(String formatName)
{
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
new ContainsFilter(writerFormatNamesMethod,
formatName),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageWriter>emptyList().iterator();
}
return new ImageWriterIterator(iter);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageWriter</code>s that claim to be able to
* encode files with the given suffix.
*
* @param fileSuffix a <code>String</code> containing a file
* suffix (<i>e.g.</i>, "jpg" or "tiff").
*
* @return an <code>Iterator</code> containing <code>ImageWriter</code>s.
*
* @exception IllegalArgumentException if <code>fileSuffix</code> is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageWriterSpi#getFileSuffixes
*/
public static Iterator<ImageWriter>
getImageWritersBySuffix(String fileSuffix)
{
if (fileSuffix == null) {
throw new IllegalArgumentException("fileSuffix == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
new ContainsFilter(writerFileSuffixesMethod,
fileSuffix),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageWriter>emptyList().iterator();
}
return new ImageWriterIterator(iter);
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageWriter</code>s that claim to be able to
* encode files with the given MIME type.
*
* @param MIMEType a <code>String</code> containing a file
* suffix (<i>e.g.</i>, "image/jpeg" or "image/x-bmp").
*
* @return an <code>Iterator</code> containing <code>ImageWriter</code>s.
*
* @exception IllegalArgumentException if <code>MIMEType</code> is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageWriterSpi#getMIMETypes
*/
public static Iterator<ImageWriter>
getImageWritersByMIMEType(String MIMEType)
{
if (MIMEType == null) {
throw new IllegalArgumentException("MIMEType == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
new ContainsFilter(writerMIMETypesMethod,
MIMEType),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageWriter>emptyList().iterator();
}
return new ImageWriterIterator(iter);
}
/** {@collect.stats}
* Returns an <code>ImageWriter</code>corresponding to the given
* <code>ImageReader</code>, if there is one, or <code>null</code>
* if the plug-in for this <code>ImageReader</code> does not
* specify a corresponding <code>ImageWriter</code>, or if the
* given <code>ImageReader</code> is not registered. This
* mechanism may be used to obtain an <code>ImageWriter</code>
* that will understand the internal structure of non-pixel
* metadata (as encoded by <code>IIOMetadata</code> objects)
* generated by the <code>ImageReader</code>. By obtaining this
* data from the <code>ImageReader</code> and passing it on to the
* <code>ImageWriter</code> obtained with this method, a client
* program can read an image, modify it in some way, and write it
* back out preserving all metadata, without having to understand
* anything about the structure of the metadata, or even about
* the image format. Note that this method returns the
* "preferred" writer, which is the first in the list returned by
* <code>javax.imageio.spi.ImageReaderSpi.getImageWriterSpiNames()</code>.
*
* @param reader an instance of a registered <code>ImageReader</code>.
*
* @return an <code>ImageWriter</code>, or null.
*
* @exception IllegalArgumentException if <code>reader</code> is
* <code>null</code>.
*
* @see #getImageReader(ImageWriter)
* @see javax.imageio.spi.ImageReaderSpi#getImageWriterSpiNames()
*/
public static ImageWriter getImageWriter(ImageReader reader) {
if (reader == null) {
throw new IllegalArgumentException("reader == null!");
}
ImageReaderSpi readerSpi = reader.getOriginatingProvider();
if (readerSpi == null) {
Iterator readerSpiIter;
// Ensure category is present
try {
readerSpiIter =
theRegistry.getServiceProviders(ImageReaderSpi.class,
false);
} catch (IllegalArgumentException e) {
return null;
}
while (readerSpiIter.hasNext()) {
ImageReaderSpi temp = (ImageReaderSpi) readerSpiIter.next();
if (temp.isOwnReader(reader)) {
readerSpi = temp;
break;
}
}
if (readerSpi == null) {
return null;
}
}
String[] writerNames = readerSpi.getImageWriterSpiNames();
if (writerNames == null) {
return null;
}
Class writerSpiClass = null;
try {
writerSpiClass = Class.forName(writerNames[0], true,
ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
ImageWriterSpi writerSpi = (ImageWriterSpi)
theRegistry.getServiceProviderByClass(writerSpiClass);
if (writerSpi == null) {
return null;
}
try {
return writerSpi.createWriterInstance();
} catch (IOException e) {
// Deregister the spi in this case, but only as a writerSpi
theRegistry.deregisterServiceProvider(writerSpi,
ImageWriterSpi.class);
return null;
}
}
/** {@collect.stats}
* Returns an <code>ImageReader</code>corresponding to the given
* <code>ImageWriter</code>, if there is one, or <code>null</code>
* if the plug-in for this <code>ImageWriter</code> does not
* specify a corresponding <code>ImageReader</code>, or if the
* given <code>ImageWriter</code> is not registered. This method
* is provided principally for symmetry with
* <code>getImageWriter(ImageReader)</code>. Note that this
* method returns the "preferred" reader, which is the first in
* the list returned by
* javax.imageio.spi.ImageWriterSpi.<code>getImageReaderSpiNames()</code>.
*
* @param writer an instance of a registered <code>ImageWriter</code>.
*
* @return an <code>ImageReader</code>, or null.
*
* @exception IllegalArgumentException if <code>writer</code> is
* <code>null</code>.
*
* @see #getImageWriter(ImageReader)
* @see javax.imageio.spi.ImageWriterSpi#getImageReaderSpiNames()
*/
public static ImageReader getImageReader(ImageWriter writer) {
if (writer == null) {
throw new IllegalArgumentException("writer == null!");
}
ImageWriterSpi writerSpi = writer.getOriginatingProvider();
if (writerSpi == null) {
Iterator writerSpiIter;
// Ensure category is present
try {
writerSpiIter =
theRegistry.getServiceProviders(ImageWriterSpi.class,
false);
} catch (IllegalArgumentException e) {
return null;
}
while (writerSpiIter.hasNext()) {
ImageWriterSpi temp = (ImageWriterSpi) writerSpiIter.next();
if (temp.isOwnWriter(writer)) {
writerSpi = temp;
break;
}
}
if (writerSpi == null) {
return null;
}
}
String[] readerNames = writerSpi.getImageReaderSpiNames();
if (readerNames == null) {
return null;
}
Class readerSpiClass = null;
try {
readerSpiClass = Class.forName(readerNames[0], true,
ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e) {
return null;
}
ImageReaderSpi readerSpi = (ImageReaderSpi)
theRegistry.getServiceProviderByClass(readerSpiClass);
if (readerSpi == null) {
return null;
}
try {
return readerSpi.createReaderInstance();
} catch (IOException e) {
// Deregister the spi in this case, but only as a readerSpi
theRegistry.deregisterServiceProvider(readerSpi,
ImageReaderSpi.class);
return null;
}
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageWriter</code>s that claim to be able to
* encode images of the given layout (specified using an
* <code>ImageTypeSpecifier</code>) in the given format.
*
* @param type an <code>ImageTypeSpecifier</code> indicating the
* layout of the image to be written.
* @param formatName the informal name of the <code>format</code>.
*
* @return an <code>Iterator</code> containing <code>ImageWriter</code>s.
*
* @exception IllegalArgumentException if any parameter is
* <code>null</code>.
*
* @see javax.imageio.spi.ImageWriterSpi#canEncodeImage(ImageTypeSpecifier)
*/
public static Iterator<ImageWriter>
getImageWriters(ImageTypeSpecifier type, String formatName)
{
if (type == null) {
throw new IllegalArgumentException("type == null!");
}
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageWriterSpi.class,
new CanEncodeImageAndFormatFilter(type,
formatName),
true);
} catch (IllegalArgumentException e) {
return Collections.<ImageWriter>emptyList().iterator();
}
return new ImageWriterIterator(iter);
}
static class ImageTranscoderIterator
implements Iterator<ImageTranscoder>
{
// Contains ImageTranscoderSpis
public Iterator iter;
public ImageTranscoderIterator(Iterator iter) {
this.iter = iter;
}
public boolean hasNext() {
return iter.hasNext();
}
public ImageTranscoder next() {
ImageTranscoderSpi spi = null;
spi = (ImageTranscoderSpi)iter.next();
return spi.createTranscoderInstance();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
static class TranscoderFilter
implements ServiceRegistry.Filter {
String readerSpiName;
String writerSpiName;
public TranscoderFilter(ImageReaderSpi readerSpi,
ImageWriterSpi writerSpi) {
this.readerSpiName = readerSpi.getClass().getName();
this.writerSpiName = writerSpi.getClass().getName();
}
public boolean filter(Object elt) {
ImageTranscoderSpi spi = (ImageTranscoderSpi)elt;
String readerName = spi.getReaderServiceProviderName();
String writerName = spi.getWriterServiceProviderName();
return (readerName.equals(readerSpiName) &&
writerName.equals(writerSpiName));
}
}
/** {@collect.stats}
* Returns an <code>Iterator</code> containing all currently
* registered <code>ImageTranscoder</code>s that claim to be
* able to transcode between the metadata of the given
* <code>ImageReader</code> and <code>ImageWriter</code>.
*
* @param reader an <code>ImageReader</code>.
* @param writer an <code>ImageWriter</code>.
*
* @return an <code>Iterator</code> containing
* <code>ImageTranscoder</code>s.
*
* @exception IllegalArgumentException if <code>reader</code> or
* <code>writer</code> is <code>null</code>.
*/
public static Iterator<ImageTranscoder>
getImageTranscoders(ImageReader reader, ImageWriter writer)
{
if (reader == null) {
throw new IllegalArgumentException("reader == null!");
}
if (writer == null) {
throw new IllegalArgumentException("writer == null!");
}
ImageReaderSpi readerSpi = reader.getOriginatingProvider();
ImageWriterSpi writerSpi = writer.getOriginatingProvider();
ServiceRegistry.Filter filter =
new TranscoderFilter(readerSpi, writerSpi);
Iterator iter;
// Ensure category is present
try {
iter = theRegistry.getServiceProviders(ImageTranscoderSpi.class,
filter, true);
} catch (IllegalArgumentException e) {
return Collections.<ImageTranscoder>emptyList().iterator();
}
return new ImageTranscoderIterator(iter);
}
// All-in-one methods
/** {@collect.stats}
* Returns a <code>BufferedImage</code> as the result of decoding
* a supplied <code>File</code> with an <code>ImageReader</code>
* chosen automatically from among those currently registered.
* The <code>File</code> is wrapped in an
* <code>ImageInputStream</code>. If no registered
* <code>ImageReader</code> claims to be able to read the
* resulting stream, <code>null</code> is returned.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching in the
* <code>ImageInputStream</code> that is created.
*
* <p> Note that there is no <code>read</code> method that takes a
* filename as a <code>String</code>; use this method instead after
* creating a <code>File</code> from the filename.
*
* <p> This method does not attempt to locate
* <code>ImageReader</code>s that can read directly from a
* <code>File</code>; that may be accomplished using
* <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
*
* @param input a <code>File</code> to read from.
*
* @return a <code>BufferedImage</code> containing the decoded
* contents of the input, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>input</code> is
* <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public static BufferedImage read(File input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
if (!input.canRead()) {
throw new IIOException("Can't read input file!");
}
ImageInputStream stream = createImageInputStream(input);
if (stream == null) {
throw new IIOException("Can't create an ImageInputStream!");
}
BufferedImage bi = read(stream);
if (bi == null) {
stream.close();
}
return bi;
}
/** {@collect.stats}
* Returns a <code>BufferedImage</code> as the result of decoding
* a supplied <code>InputStream</code> with an <code>ImageReader</code>
* chosen automatically from among those currently registered.
* The <code>InputStream</code> is wrapped in an
* <code>ImageInputStream</code>. If no registered
* <code>ImageReader</code> claims to be able to read the
* resulting stream, <code>null</code> is returned.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching in the
* <code>ImageInputStream</code> that is created.
*
* <p> This method does not attempt to locate
* <code>ImageReader</code>s that can read directly from an
* <code>InputStream</code>; that may be accomplished using
* <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
*
* <p> This method <em>does not</em> close the provided
* <code>InputStream</code> after the read operation has completed;
* it is the responsibility of the caller to close the stream, if desired.
*
* @param input an <code>InputStream</code> to read from.
*
* @return a <code>BufferedImage</code> containing the decoded
* contents of the input, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>input</code> is
* <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public static BufferedImage read(InputStream input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
ImageInputStream stream = createImageInputStream(input);
BufferedImage bi = read(stream);
if (bi == null) {
stream.close();
}
return bi;
}
/** {@collect.stats}
* Returns a <code>BufferedImage</code> as the result of decoding
* a supplied <code>URL</code> with an <code>ImageReader</code>
* chosen automatically from among those currently registered. An
* <code>InputStream</code> is obtained from the <code>URL</code>,
* which is wrapped in an <code>ImageInputStream</code>. If no
* registered <code>ImageReader</code> claims to be able to read
* the resulting stream, <code>null</code> is returned.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching in the
* <code>ImageInputStream</code> that is created.
*
* <p> This method does not attempt to locate
* <code>ImageReader</code>s that can read directly from a
* <code>URL</code>; that may be accomplished using
* <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
*
* @param input a <code>URL</code> to read from.
*
* @return a <code>BufferedImage</code> containing the decoded
* contents of the input, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>input</code> is
* <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public static BufferedImage read(URL input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
InputStream istream = null;
try {
istream = input.openStream();
} catch (IOException e) {
throw new IIOException("Can't get input stream from URL!", e);
}
ImageInputStream stream = createImageInputStream(istream);
BufferedImage bi;
try {
bi = read(stream);
if (bi == null) {
stream.close();
}
} finally {
istream.close();
}
return bi;
}
/** {@collect.stats}
* Returns a <code>BufferedImage</code> as the result of decoding
* a supplied <code>ImageInputStream</code> with an
* <code>ImageReader</code> chosen automatically from among those
* currently registered. If no registered
* <code>ImageReader</code> claims to be able to read the stream,
* <code>null</code> is returned.
*
* <p> Unlike most other methods in this class, this method <em>does</em>
* close the provided <code>ImageInputStream</code> after the read
* operation has completed, unless <code>null</code> is returned,
* in which case this method <em>does not</em> close the stream.
*
* @param stream an <code>ImageInputStream</code> to read from.
*
* @return a <code>BufferedImage</code> containing the decoded
* contents of the input, or <code>null</code>.
*
* @exception IllegalArgumentException if <code>stream</code> is
* <code>null</code>.
* @exception IOException if an error occurs during reading.
*/
public static BufferedImage read(ImageInputStream stream)
throws IOException {
if (stream == null) {
throw new IllegalArgumentException("stream == null!");
}
Iterator iter = getImageReaders(stream);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader)iter.next();
ImageReadParam param = reader.getDefaultReadParam();
reader.setInput(stream, true, true);
BufferedImage bi;
try {
bi = reader.read(0, param);
} finally {
reader.dispose();
stream.close();
}
return bi;
}
/** {@collect.stats}
* Writes an image using the an arbitrary <code>ImageWriter</code>
* that supports the given format to an
* <code>ImageOutputStream</code>. The image is written to the
* <code>ImageOutputStream</code> starting at the current stream
* pointer, overwriting existing stream data from that point
* forward, if present.
*
* <p> This method <em>does not</em> close the provided
* <code>ImageOutputStream</code> after the write operation has completed;
* it is the responsibility of the caller to close the stream, if desired.
*
* @param im a <code>RenderedImage</code> to be written.
* @param formatName a <code>String</code> containg the informal
* name of the format.
* @param output an <code>ImageOutputStream</code> to be written to.
*
* @return <code>false</code> if no appropriate writer is found.
*
* @exception IllegalArgumentException if any parameter is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public static boolean write(RenderedImage im,
String formatName,
ImageOutputStream output) throws IOException {
if (im == null) {
throw new IllegalArgumentException("im == null!");
}
if (formatName == null) {
throw new IllegalArgumentException("formatName == null!");
}
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
return doWrite(im, getWriter(im, formatName), output);
}
/** {@collect.stats}
* Writes an image using an arbitrary <code>ImageWriter</code>
* that supports the given format to a <code>File</code>. If
* there is already a <code>File</code> present, its contents are
* discarded.
*
* @param im a <code>RenderedImage</code> to be written.
* @param formatName a <code>String</code> containg the informal
* name of the format.
* @param output a <code>File</code> to be written to.
*
* @return <code>false</code> if no appropriate writer is found.
*
* @exception IllegalArgumentException if any parameter is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public static boolean write(RenderedImage im,
String formatName,
File output) throws IOException {
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
ImageOutputStream stream = null;
ImageWriter writer = getWriter(im, formatName);
if (writer == null) {
/* Do not make changes in the file system if we have
* no appropriate writer.
*/
return false;
}
try {
output.delete();
stream = createImageOutputStream(output);
} catch (IOException e) {
throw new IIOException("Can't create output stream!", e);
}
try {
return doWrite(im, writer, stream);
} finally {
stream.close();
}
}
/** {@collect.stats}
* Writes an image using an arbitrary <code>ImageWriter</code>
* that supports the given format to an <code>OutputStream</code>.
*
* <p> This method <em>does not</em> close the provided
* <code>OutputStream</code> after the write operation has completed;
* it is the responsibility of the caller to close the stream, if desired.
*
* <p> The current cache settings from <code>getUseCache</code>and
* <code>getCacheDirectory</code> will be used to control caching.
*
* @param im a <code>RenderedImage</code> to be written.
* @param formatName a <code>String</code> containg the informal
* name of the format.
* @param output an <code>OutputStream</code> to be written to.
*
* @return <code>false</code> if no appropriate writer is found.
*
* @exception IllegalArgumentException if any parameter is
* <code>null</code>.
* @exception IOException if an error occurs during writing.
*/
public static boolean write(RenderedImage im,
String formatName,
OutputStream output) throws IOException {
if (output == null) {
throw new IllegalArgumentException("output == null!");
}
ImageOutputStream stream = null;
try {
stream = createImageOutputStream(output);
} catch (IOException e) {
throw new IIOException("Can't create output stream!", e);
}
try {
return doWrite(im, getWriter(im, formatName), stream);
} finally {
stream.close();
}
}
/** {@collect.stats}
* Returns <code>ImageWriter</code> instance according to given
* rendered image and image format or <code>null</code> if there
* is no appropriate writer.
*/
private static ImageWriter getWriter(RenderedImage im,
String formatName) {
ImageTypeSpecifier type =
ImageTypeSpecifier.createFromRenderedImage(im);
Iterator<ImageWriter> iter = getImageWriters(type, formatName);
if (iter.hasNext()) {
return iter.next();
} else {
return null;
}
}
/** {@collect.stats}
* Writes image to output stream using given image writer.
*/
private static boolean doWrite(RenderedImage im, ImageWriter writer,
ImageOutputStream output) throws IOException {
if (writer == null) {
return false;
}
writer.setOutput(output);
try {
writer.write(im);
} finally {
writer.dispose();
output.flush();
}
return true;
}
}
|
Java
|
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.io.IOException;
/** {@collect.stats}
* An exception class used for signaling run-time failure of reading
* and writing operations.
*
* <p> In addition to a message string, a reference to another
* <code>Throwable</code> (<code>Error</code> or
* <code>Exception</code>) is maintained. This reference, if
* non-<code>null</code>, refers to the event that caused this
* exception to occur. For example, an <code>IOException</code> while
* reading from a <code>File</code> would be stored there.
*
*/
public class IIOException extends IOException {
/** {@collect.stats}
* Constructs an <code>IIOException</code> with a given message
* <code>String</code>. No underlying cause is set;
* <code>getCause</code> will return <code>null</code>.
*
* @param message the error message.
*
* @see #getMessage
*/
public IIOException(String message) {
super(message);
}
/** {@collect.stats}
* Constructs an <code>IIOException</code> with a given message
* <code>String</code> and a <code>Throwable</code> that was its
* underlying cause.
*
* @param message the error message.
* @param cause the <code>Throwable</code> (<code>Error</code> or
* <code>Exception</code>) that caused this exception to occur.
*
* @see #getCause
* @see #getMessage
*/
public IIOException(String message, Throwable cause) {
super(message);
initCause(cause);
}
}
|
Java
|
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.imageio;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
/** {@collect.stats}
* A class describing how a stream is to be decoded. Instances of
* this class or its subclasses are used to supply prescriptive
* "how-to" information to instances of <code>ImageReader</code>.
*
* <p> An image encoded as part of a file or stream may be thought of
* extending out in multiple dimensions: the spatial dimensions of
* width and height, a number of bands, and a number of progressive
* decoding passes. This class allows a contiguous (hyper)rectangular
* subarea of the image in all of these dimensions to be selected for
* decoding. Additionally, the spatial dimensions may be subsampled
* discontinuously. Finally, color and format conversions may be
* specified by controlling the <code>ColorModel</code> and
* <code>SampleModel</code> of the destination image, either by
* providing a <code>BufferedImage</code> or by using an
* <code>ImageTypeSpecifier</code>.
*
* <p> An <code>ImageReadParam</code> object is used to specify how an
* image, or a set of images, will be converted on input from
* a stream in the context of the Java Image I/O framework. A plug-in for a
* specific image format will return instances of
* <code>ImageReadParam</code> from the
* <code>getDefaultReadParam</code> method of its
* <code>ImageReader</code> implementation.
*
* <p> The state maintained by an instance of
* <code>ImageReadParam</code> is independent of any particular image
* being decoded. When actual decoding takes place, the values set in
* the read param are combined with the actual properties of the image
* being decoded from the stream and the destination
* <code>BufferedImage</code> that will receive the decoded pixel
* data. For example, the source region set using
* <code>setSourceRegion</code> will first be intersected with the
* actual valid source area. The result will be translated by the
* value returned by <code>getDestinationOffset</code>, and the
* resulting rectangle intersected with the actual valid destination
* area to yield the destination area that will be written.
*
* <p> The parameters specified by an <code>ImageReadParam</code> are
* applied to an image as follows. First, if a rendering size has
* been set by <code>setSourceRenderSize</code>, the entire decoded
* image is rendered at the size given by
* <code>getSourceRenderSize</code>. Otherwise, the image has its
* natural size given by <code>ImageReader.getWidth</code> and
* <code>ImageReader.getHeight</code>.
*
* <p> Next, the image is clipped against the source region
* specified by <code>getSourceXOffset</code>, <code>getSourceYOffset</code>,
* <code>getSourceWidth</code>, and <code>getSourceHeight</code>.
*
* <p> The resulting region is then subsampled according to the
* factors given in {@link IIOParam#setSourceSubsampling
* <code>IIOParam.setSourceSubsampling</code>}. The first pixel,
* the number of pixels per row, and the number of rows all depend
* on the subsampling settings.
* Call the minimum X and Y coordinates of the resulting rectangle
* (<code>minX</code>, <code>minY</code>), its width <code>w</code>
* and its height <code>h</code>.
*
* <p> This rectangle is offset by
* (<code>getDestinationOffset().x</code>,
* <code>getDestinationOffset().y</code>) and clipped against the
* destination bounds. If no destination image has been set, the
* destination is defined to have a width of
* <code>getDestinationOffset().x</code> + <code>w</code>, and a
* height of <code>getDestinationOffset().y</code> + <code>h</code> so
* that all pixels of the source region may be written to the
* destination.
*
* <p> Pixels that land, after subsampling, within the destination
* image, and that are written in one of the progressive passes
* specified by <code>getSourceMinProgressivePass</code> and
* <code>getSourceNumProgressivePasses</code> are passed along to the
* next step.
*
* <p> Finally, the source samples of each pixel are mapped into
* destination bands according to the algorithm described in the
* comment for <code>setDestinationBands</code>.
*
* <p> Plug-in writers may extend the functionality of
* <code>ImageReadParam</code> by providing a subclass that implements
* additional, plug-in specific interfaces. It is up to the plug-in
* to document what interfaces are available and how they are to be
* used. Readers will silently ignore any extended features of an
* <code>ImageReadParam</code> subclass of which they are not aware.
* Also, they may ignore any optional features that they normally
* disable when creating their own <code>ImageReadParam</code>
* instances via <code>getDefaultReadParam</code>.
*
* <p> Note that unless a query method exists for a capability, it must
* be supported by all <code>ImageReader</code> implementations
* (<i>e.g.</i> source render size is optional, but subsampling must be
* supported).
*
*
* @see ImageReader
* @see ImageWriter
* @see ImageWriteParam
*/
public class ImageReadParam extends IIOParam {
/** {@collect.stats}
* <code>true</code> if this <code>ImageReadParam</code> allows
* the source rendering dimensions to be set. By default, the
* value is <code>false</code>. Subclasses must set this value
* manually.
*
* <p> <code>ImageReader</code>s that do not support setting of
* the source render size should set this value to
* <code>false</code>.
*/
protected boolean canSetSourceRenderSize = false;
/** {@collect.stats}
* The desired rendering width and height of the source, if
* <code>canSetSourceRenderSize</code> is <code>true</code>, or
* <code>null</code>.
*
* <p> <code>ImageReader</code>s that do not support setting of
* the source render size may ignore this value.
*/
protected Dimension sourceRenderSize = null;
/** {@collect.stats}
* The current destination <code>BufferedImage</code>, or
* <code>null</code> if none has been set. By default, the value
* is <code>null</code>.
*/
protected BufferedImage destination = null;
/** {@collect.stats}
* The set of destination bands to be used, as an array of
* <code>int</code>s. By default, the value is <code>null</code>,
* indicating all destination bands should be written in order.
*/
protected int[] destinationBands = null;
/** {@collect.stats}
* The minimum index of a progressive pass to read from the
* source. By default, the value is set to 0, which indicates
* that passes starting with the first available pass should be
* decoded.
*
* <p> Subclasses should ensure that this value is
* non-negative.
*/
protected int minProgressivePass = 0;
/** {@collect.stats}
* The maximum number of progressive passes to read from the
* source. By default, the value is set to
* <code>Integer.MAX_VALUE</code>, which indicates that passes up
* to and including the last available pass should be decoded.
*
* <p> Subclasses should ensure that this value is positive.
* Additionally, if the value is not
* <code>Integer.MAX_VALUE</code>, then <code>minProgressivePass +
* numProgressivePasses - 1</code> should not exceed
* <code>Integer.MAX_VALUE</code>.
*/
protected int numProgressivePasses = Integer.MAX_VALUE;
/** {@collect.stats}
* Constructs an <code>ImageReadParam</code>.
*/
public ImageReadParam() {}
// Comment inherited
public void setDestinationType(ImageTypeSpecifier destinationType) {
super.setDestinationType(destinationType);
setDestination(null);
}
/** {@collect.stats}
* Supplies a <code>BufferedImage</code> to be used as the
* destination for decoded pixel data. The currently set image
* will be written to by the <code>read</code>,
* <code>readAll</code>, and <code>readRaster</code> methods, and
* a reference to it will be returned by those methods.
*
* <p> Pixel data from the aforementioned methods will be written
* starting at the offset specified by
* <code>getDestinationOffset</code>.
*
* <p> If <code>destination</code> is <code>null</code>, a
* newly-created <code>BufferedImage</code> will be returned by
* those methods.
*
* <p> At the time of reading, the image is checked to verify that
* its <code>ColorModel</code> and <code>SampleModel</code>
* correspond to one of the <code>ImageTypeSpecifier</code>s
* returned from the <code>ImageReader</code>'s
* <code>getImageTypes</code> method. If it does not, the reader
* will throw an <code>IIOException</code>.
*
* @param destination the BufferedImage to be written to, or
* <code>null</code>.
*
* @see #getDestination
*/
public void setDestination(BufferedImage destination) {
this.destination = destination;
}
/** {@collect.stats}
* Returns the <code>BufferedImage</code> currently set by the
* <code>setDestination</code> method, or <code>null</code>
* if none is set.
*
* @return the BufferedImage to be written to.
*
* @see #setDestination
*/
public BufferedImage getDestination() {
return destination;
}
/** {@collect.stats}
* Sets the indices of the destination bands where data
* will be placed. Duplicate indices are not allowed.
*
* <p> A <code>null</code> value indicates that all destination
* bands will be used.
*
* <p> Choosing a destination band subset will not affect the
* number of bands in the output image of a read if no destination
* image is specified; the created destination image will still
* have the same number of bands as if this method had never been
* called. If a different number of bands in the destination
* image is desired, an image must be supplied using the
* <code>ImageReadParam.setDestination</code> method.
*
* <p> At the time of reading or writing, an
* <code>IllegalArgumentException</code> will be thrown by the
* reader or writer if a value larger than the largest destination
* band index has been specified, or if the number of source bands
* and destination bands to be used differ. The
* <code>ImageReader.checkReadParamBandSettings</code> method may
* be used to automate this test.
*
* @param destinationBands an array of integer band indices to be
* used.
*
* @exception IllegalArgumentException if <code>destinationBands</code>
* contains a negative or duplicate value.
*
* @see #getDestinationBands
* @see #getSourceBands
* @see ImageReader#checkReadParamBandSettings
*/
public void setDestinationBands(int[] destinationBands) {
if (destinationBands == null) {
this.destinationBands = null;
} else {
int numBands = destinationBands.length;
for (int i = 0; i < numBands; i++) {
int band = destinationBands[i];
if (band < 0) {
throw new IllegalArgumentException("Band value < 0!");
}
for (int j = i + 1; j < numBands; j++) {
if (band == destinationBands[j]) {
throw new IllegalArgumentException("Duplicate band value!");
}
}
}
this.destinationBands = (int[])destinationBands.clone();
}
}
/** {@collect.stats}
* Returns the set of band indices where data will be placed.
* If no value has been set, <code>null</code> is returned to
* indicate that all destination bands will be used.
*
* @return the indices of the destination bands to be used,
* or <code>null</code>.
*
* @see #setDestinationBands
*/
public int[] getDestinationBands() {
if (destinationBands == null) {
return null;
} else {
return (int[])(destinationBands.clone());
}
}
/** {@collect.stats}
* Returns <code>true</code> if this reader allows the source
* image to be rendered at an arbitrary size as part of the
* decoding process, by means of the
* <code>setSourceRenderSize</code> method. If this method
* returns <code>false</code>, calls to
* <code>setSourceRenderSize</code> will throw an
* <code>UnsupportedOperationException</code>.
*
* @return <code>true</code> if setting source rendering size is
* supported.
*
* @see #setSourceRenderSize
*/
public boolean canSetSourceRenderSize() {
return canSetSourceRenderSize;
}
/** {@collect.stats}
* If the image is able to be rendered at an arbitrary size, sets
* the source width and height to the supplied values. Note that
* the values returned from the <code>getWidth</code> and
* <code>getHeight</code> methods on <code>ImageReader</code> are
* not affected by this method; they will continue to return the
* default size for the image. Similarly, if the image is also
* tiled the tile width and height are given in terms of the default
* size.
*
* <p> Typically, the width and height should be chosen such that
* the ratio of width to height closely approximates the aspect
* ratio of the image, as returned from
* <code>ImageReader.getAspectRatio</code>.
*
* <p> If this plug-in does not allow the rendering size to be
* set, an <code>UnsupportedOperationException</code> will be
* thrown.
*
* <p> To remove the render size setting, pass in a value of
* <code>null</code> for <code>size</code>.
*
* @param size a <code>Dimension</code> indicating the desired
* width and height.
*
* @exception IllegalArgumentException if either the width or the
* height is negative or 0.
* @exception UnsupportedOperationException if image resizing
* is not supported by this plug-in.
*
* @see #getSourceRenderSize
* @see ImageReader#getWidth
* @see ImageReader#getHeight
* @see ImageReader#getAspectRatio
*/
public void setSourceRenderSize(Dimension size)
throws UnsupportedOperationException {
if (!canSetSourceRenderSize()) {
throw new UnsupportedOperationException
("Can't set source render size!");
}
if (size == null) {
this.sourceRenderSize = null;
} else {
if (size.width <= 0 || size.height <= 0) {
throw new IllegalArgumentException("width or height <= 0!");
}
this.sourceRenderSize = (Dimension)size.clone();
}
}
/** {@collect.stats}
* Returns the width and height of the source image as it
* will be rendered during decoding, if they have been set via the
* <code>setSourceRenderSize</code> method. A
* <code>null</code>value indicates that no setting has been made.
*
* @return the rendered width and height of the source image
* as a <code>Dimension</code>.
*
* @see #setSourceRenderSize
*/
public Dimension getSourceRenderSize() {
return (sourceRenderSize == null) ?
null : (Dimension)sourceRenderSize.clone();
}
/** {@collect.stats}
* Sets the range of progressive passes that will be decoded.
* Passes outside of this range will be ignored.
*
* <p> A progressive pass is a re-encoding of the entire image,
* generally at progressively higher effective resolutions, but
* requiring greater transmission bandwidth. The most common use
* of progressive encoding is found in the JPEG format, where
* successive passes include more detailed representations of the
* high-frequency image content.
*
* <p> The actual number of passes to be decoded is determined
* during decoding, based on the number of actual passes available
* in the stream. Thus if <code>minPass + numPasses - 1</code> is
* larger than the index of the last available passes, decoding
* will end with that pass.
*
* <p> A value of <code>numPasses</code> of
* <code>Integer.MAX_VALUE</code> indicates that all passes from
* <code>minPass</code> forward should be read. Otherwise, the
* index of the last pass (<i>i.e.</i>, <code>minPass + numPasses
* - 1</code>) must not exceed <code>Integer.MAX_VALUE</code>.
*
* <p> There is no <code>unsetSourceProgressivePasses</code>
* method; the same effect may be obtained by calling
* <code>setSourceProgressivePasses(0, Integer.MAX_VALUE)</code>.
*
* @param minPass the index of the first pass to be decoded.
* @param numPasses the maximum number of passes to be decoded.
*
* @exception IllegalArgumentException if <code>minPass</code> is
* negative, <code>numPasses</code> is negative or 0, or
* <code>numPasses</code> is smaller than
* <code>Integer.MAX_VALUE</code> but <code>minPass +
* numPasses - 1</code> is greater than
* <code>INTEGER.MAX_VALUE</code>.
*
* @see #getSourceMinProgressivePass
* @see #getSourceMaxProgressivePass
*/
public void setSourceProgressivePasses(int minPass, int numPasses) {
if (minPass < 0) {
throw new IllegalArgumentException("minPass < 0!");
}
if (numPasses <= 0) {
throw new IllegalArgumentException("numPasses <= 0!");
}
if ((numPasses != Integer.MAX_VALUE) &&
(((minPass + numPasses - 1) & 0x80000000) != 0)) {
throw new IllegalArgumentException
("minPass + numPasses - 1 > INTEGER.MAX_VALUE!");
}
this.minProgressivePass = minPass;
this.numProgressivePasses = numPasses;
}
/** {@collect.stats}
* Returns the index of the first progressive pass that will be
* decoded. If no value has been set, 0 will be returned (which is
* the correct value).
*
* @return the index of the first pass that will be decoded.
*
* @see #setSourceProgressivePasses
* @see #getSourceNumProgressivePasses
*/
public int getSourceMinProgressivePass() {
return minProgressivePass;
}
/** {@collect.stats}
* If <code>getSourceNumProgressivePasses</code> is equal to
* <code>Integer.MAX_VALUE</code>, returns
* <code>Integer.MAX_VALUE</code>. Otherwise, returns
* <code>getSourceMinProgressivePass() +
* getSourceNumProgressivePasses() - 1</code>.
*
* @return the index of the last pass to be read, or
* <code>Integer.MAX_VALUE</code>.
*/
public int getSourceMaxProgressivePass() {
if (numProgressivePasses == Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else {
return minProgressivePass + numProgressivePasses - 1;
}
}
/** {@collect.stats}
* Returns the number of the progressive passes that will be
* decoded. If no value has been set,
* <code>Integer.MAX_VALUE</code> will be returned (which is the
* correct value).
*
* @return the number of the passes that will be decoded.
*
* @see #setSourceProgressivePasses
* @see #getSourceMinProgressivePass
*/
public int getSourceNumProgressivePasses() {
return numProgressivePasses;
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown to indicate that the result being returned
* or returned so far is partial, and that the operation cannot
* be completed. For example, when listing a context, this exception
* indicates that returned results only represents some of the bindings
* in the context.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class PartialResultException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of the exception using the explanation
* message specified. All other fields default to null.
*
* @param explanation Possibly null detail explaining the exception.
*/
public PartialResultException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of PartialResultException.
* All fields default to null.
*/
public PartialResultException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 2572144970049426786L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This class represents a name-to-object binding found in a context.
*<p>
* A context consists of name-to-object bindings.
* The Binding class represents such a binding. It consists
* of a name and an object. The <code>Context.listBindings()</code>
* method returns an enumeration of Binding.
*<p>
* Use subclassing for naming systems that generate contents of
* a binding dynamically.
*<p>
* A Binding instance is not synchronized against concurrent access by multiple
* threads. Threads that need to access a Binding concurrently should
* synchronize amongst themselves and provide the necessary locking.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class Binding extends NameClassPair {
/** {@collect.stats}
* Contains this binding's object.
* It is initialized by the constuctor and can be updated using
* <tt>setObject</tt>.
* @serial
* @see #getObject
* @see #setObject
*/
private Object boundObj;
/** {@collect.stats}
* Constructs an instance of a Binding given its name and object.
*<p>
* <tt>getClassName()</tt> will return
* the class name of <tt>obj</tt> (or null if <tt>obj</tt> is null)
* unless the class name has been explicitly set using <tt>setClassName()</tt>
*
* @param name The non-null name of the object. It is relative
* to the <em>target context</em> (which is
* named by the first parameter of the <code>listBindings()</code> method)
* @param obj The possibly null object bound to name.
* @see NameClassPair#setClassName
*/
public Binding(String name, Object obj) {
super(name, null);
this.boundObj = obj;
}
/** {@collect.stats}
* Constructs an instance of a Binding given its name, object, and whether
* the name is relative.
*<p>
* <tt>getClassName()</tt> will return the class name of <tt>obj</tt>
* (or null if <tt>obj</tt> is null) unless the class name has been
* explicitly set using <tt>setClassName()</tt>
*
* @param name The non-null string name of the object.
* @param obj The possibly null object bound to name.
* @param isRelative true if <code>name</code> is a name relative
* to the target context (which is named by
* the first parameter of the <code>listBindings()</code> method);
* false if <code>name</code> is a URL string.
* @see NameClassPair#isRelative
* @see NameClassPair#setRelative
* @see NameClassPair#setClassName
*/
public Binding(String name, Object obj, boolean isRelative) {
super(name, null, isRelative);
this.boundObj = obj;
}
/** {@collect.stats}
* Constructs an instance of a Binding given its name, class name, and object.
*
* @param name The non-null name of the object. It is relative
* to the <em>target context</em> (which is
* named by the first parameter of the <code>listBindings()</code> method)
* @param className The possibly null class name of the object
* bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
* returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also
* null, <tt>getClassName()</tt> will return null.
* @param obj The possibly null object bound to name.
* @see NameClassPair#setClassName
*/
public Binding(String name, String className, Object obj) {
super(name, className);
this.boundObj = obj;
}
/** {@collect.stats}
* Constructs an instance of a Binding given its
* name, class name, object, and whether the name is relative.
*
* @param name The non-null string name of the object.
* @param className The possibly null class name of the object
* bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
* returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also
* null, <tt>getClassName()</tt> will return null.
* @param obj The possibly null object bound to name.
* @param isRelative true if <code>name</code> is a name relative
* to the target context (which is named by
* the first parameter of the <code>listBindings()</code> method);
* false if <code>name</code> is a URL string.
* @see NameClassPair#isRelative
* @see NameClassPair#setRelative
* @see NameClassPair#setClassName
*/
public Binding(String name, String className, Object obj, boolean isRelative) {
super(name, className, isRelative);
this.boundObj = obj;
}
/** {@collect.stats}
* Retrieves the class name of the object bound to the name of this binding.
* If the class name has been set explicitly, return it.
* Otherwise, if this binding contains a non-null object,
* that object's class name is used. Otherwise, null is returned.
*
* @return A possibly null string containing class name of object bound.
*/
public String getClassName() {
String cname = super.getClassName();
if (cname != null) {
return cname;
}
if (boundObj != null)
return boundObj.getClass().getName();
else
return null;
}
/** {@collect.stats}
* Retrieves the object bound to the name of this binding.
*
* @return The object bound; null if this binding does not contain an object.
* @see #setObject
*/
public Object getObject() {
return boundObj;
}
/** {@collect.stats}
* Sets the object associated with this binding.
* @param obj The possibly null object to use.
* @see #getObject
*/
public void setObject(Object obj) {
boundObj = obj;
}
/** {@collect.stats}
* Generates the string representation of this binding.
* The string representation consists of the string representation
* of the name/class pair and the string representation of
* this binding's object, separated by ':'.
* The contents of this string is useful
* for debugging and is not meant to be interpreted programmatically.
*
* @return The non-null string representation of this binding.
*/
public String toString() {
return super.toString() + ":" + getObject();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 8839217842691845890L;
};
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import java.util.Vector;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import javax.naming.OperationNotSupportedException;
/** {@collect.stats}
* This interface represents an attribute associated with a named object.
*<p>
* In a directory, named objects can have associated with them
* attributes. The <tt>Attribute</tt> interface represents an attribute associated
* with a named object. An attribute contains 0 or more, possibly null, values.
* The attribute values can be ordered or unordered (see <tt>isOrdered()</tt>).
* If the values are unordered, no duplicates are allowed.
* If the values are ordered, duplicates are allowed.
*<p>
* The content and representation of an attribute and its values is defined by
* the attribute's <em>schema</em>. The schema contains information
* about the attribute's syntax and other properties about the attribute.
* See <tt>getAttributeDefinition()</tt> and
* <tt>getAttributeSyntaxDefinition()</tt>
* for details regarding how to get schema information about an attribute
* if the underlying directory service supports schemas.
*<p>
* Equality of two attributes is determined by the implementation class.
* A simple implementation can use <tt>Object.equals()</tt> to determine equality
* of attribute values, while a more sophisticated implementation might
* make use of schema information to determine equality.
* Similarly, one implementation might provide a static storage
* structure which simply returns the values passed to its
* constructor, while another implementation might define <tt>get()</tt> and
* <tt>getAll()</tt>.
* to get the values dynamically from the directory.
*<p>
* Note that updates to <tt>Attribute</tt> (such as adding or removing a
* value) do not affect the corresponding representation of the attribute
* in the directory. Updates to the directory can only be effected
* using operations in the <tt>DirContext</tt> interface.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see BasicAttribute
* @since 1.3
*/
public interface Attribute extends Cloneable, java.io.Serializable {
/** {@collect.stats}
* Retrieves an enumeration of the attribute's values.
* The behaviour of this enumeration is unspecified
* if the attribute's values are added, changed,
* or removed while the enumeration is in progress.
* If the attribute values are ordered, the enumeration's items
* will be ordered.
*
* @return A non-null enumeration of the attribute's values.
* Each element of the enumeration is a possibly null Object. The object's
* class is the class of the attribute value. The element is null
* if the attribute's value is null.
* If the attribute has zero values, an empty enumeration
* is returned.
* @exception NamingException
* If a naming exception was encountered while retrieving
* the values.
* @see #isOrdered
*/
NamingEnumeration<?> getAll() throws NamingException;
/** {@collect.stats}
* Retrieves one of this attribute's values.
* If the attribute has more than one value and is unordered, any one of
* the values is returned.
* If the attribute has more than one value and is ordered, the
* first value is returned.
*
* @return A possibly null object representing one of
* the attribute's value. It is null if the attribute's value
* is null.
* @exception NamingException
* If a naming exception was encountered while retrieving
* the value.
* @exception java.util.NoSuchElementException
* If this attribute has no values.
*/
Object get() throws NamingException;
/** {@collect.stats}
* Retrieves the number of values in this attribute.
*
* @return The nonnegative number of values in this attribute.
*/
int size();
/** {@collect.stats}
* Retrieves the id of this attribute.
*
* @return The id of this attribute. It cannot be null.
*/
String getID();
/** {@collect.stats}
* Determines whether a value is in the attribute.
* Equality is determined by the implementation, which may use
* <tt>Object.equals()</tt> or schema information to determine equality.
*
* @param attrVal The possibly null value to check. If null, check
* whether the attribute has an attribute value whose value is null.
* @return true if attrVal is one of this attribute's values; false otherwise.
* @see java.lang.Object#equals
* @see BasicAttribute#equals
*/
boolean contains(Object attrVal);
/** {@collect.stats}
* Adds a new value to the attribute.
* If the attribute values are unordered and
* <tt>attrVal</tt> is already in the attribute, this method does nothing.
* If the attribute values are ordered, <tt>attrVal</tt> is added to the end of
* the list of attribute values.
*<p>
* Equality is determined by the implementation, which may use
* <tt>Object.equals()</tt> or schema information to determine equality.
*
* @param attrVal The new possibly null value to add. If null, null
* is added as an attribute value.
* @return true if a value was added; false otherwise.
*/
boolean add(Object attrVal);
/** {@collect.stats}
* Removes a specified value from the attribute.
* If <tt>attrval</tt> is not in the attribute, this method does nothing.
* If the attribute values are ordered, the first occurrence of
* <tt>attrVal</tt> is removed and attribute values at indices greater
* than the removed
* value are shifted up towards the head of the list (and their indices
* decremented by one).
*<p>
* Equality is determined by the implementation, which may use
* <tt>Object.equals()</tt> or schema information to determine equality.
*
* @param attrval The possibly null value to remove from this attribute.
* If null, remove the attribute value that is null.
* @return true if the value was removed; false otherwise.
*/
boolean remove(Object attrval);
/** {@collect.stats}
* Removes all values from this attribute.
*/
void clear();
/** {@collect.stats}
* Retrieves the syntax definition associated with the attribute.
* An attribute's syntax definition specifies the format
* of the attribute's value(s). Note that this is different from
* the attribute value's representation as a Java object. Syntax
* definition refers to the directory's notion of <em>syntax</em>.
*<p>
* For example, even though a value might be
* a Java String object, its directory syntax might be "Printable String"
* or "Telephone Number". Or a value might be a byte array, and its
* directory syntax is "JPEG" or "Certificate".
* For example, if this attribute's syntax is "JPEG",
* this method would return the syntax definition for "JPEG".
* <p>
* The information that you can retrieve from a syntax definition
* is directory-dependent.
*<p>
* If an implementation does not support schemas, it should throw
* OperationNotSupportedException. If an implementation does support
* schemas, it should define this method to return the appropriate
* information.
* @return The attribute's syntax definition. Null if the implementation
* supports schemas but this particular attribute does not have
* any schema information.
* @exception OperationNotSupportedException If getting the schema
* is not supported.
* @exception NamingException If a naming exception occurs while getting
* the schema.
*/
DirContext getAttributeSyntaxDefinition() throws NamingException;
/** {@collect.stats}
* Retrieves the attribute's schema definition.
* An attribute's schema definition contains information
* such as whether the attribute is multivalued or single-valued,
* the matching rules to use when comparing the attribute's values.
*
* The information that you can retrieve from an attribute definition
* is directory-dependent.
*
*<p>
* If an implementation does not support schemas, it should throw
* OperationNotSupportedException. If an implementation does support
* schemas, it should define this method to return the appropriate
* information.
* @return This attribute's schema definition. Null if the implementation
* supports schemas but this particular attribute does not have
* any schema information.
* @exception OperationNotSupportedException If getting the schema
* is not supported.
* @exception NamingException If a naming exception occurs while getting
* the schema.
*/
DirContext getAttributeDefinition() throws NamingException;
/** {@collect.stats}
* Makes a copy of the attribute.
* The copy contains the same attribute values as the original attribute:
* the attribute values are not themselves cloned.
* Changes to the copy will not affect the original and vice versa.
*
* @return A non-null copy of the attribute.
*/
Object clone();
//----------- Methods to support ordered multivalued attributes
/** {@collect.stats}
* Determines whether this attribute's values are ordered.
* If an attribute's values are ordered, duplicate values are allowed.
* If an attribute's values are unordered, they are presented
* in any order and there are no duplicate values.
* @return true if this attribute's values are ordered; false otherwise.
* @see #get(int)
* @see #remove(int)
* @see #add(int, java.lang.Object)
* @see #set(int, java.lang.Object)
*/
boolean isOrdered();
/** {@collect.stats}
* Retrieves the attribute value from the ordered list of attribute values.
* This method returns the value at the <tt>ix</tt> index of the list of
* attribute values.
* If the attribute values are unordered,
* this method returns the value that happens to be at that index.
* @param ix The index of the value in the ordered list of attribute values.
* 0 <= <tt>ix</tt> < <tt>size()</tt>.
* @return The possibly null attribute value at index <tt>ix</tt>;
* null if the attribute value is null.
* @exception NamingException If a naming exception was encountered while
* retrieving the value.
* @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
*/
Object get(int ix) throws NamingException;
/** {@collect.stats}
* Removes an attribute value from the ordered list of attribute values.
* This method removes the value at the <tt>ix</tt> index of the list of
* attribute values.
* If the attribute values are unordered,
* this method removes the value that happens to be at that index.
* Values located at indices greater than <tt>ix</tt> are shifted up towards
* the front of the list (and their indices decremented by one).
*
* @param ix The index of the value to remove.
* 0 <= <tt>ix</tt> < <tt>size()</tt>.
* @return The possibly null attribute value at index <tt>ix</tt> that was removed;
* null if the attribute value is null.
* @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
*/
Object remove(int ix);
/** {@collect.stats}
* Adds an attribute value to the ordered list of attribute values.
* This method adds <tt>attrVal</tt> to the list of attribute values at
* index <tt>ix</tt>.
* Values located at indices at or greater than <tt>ix</tt> are
* shifted down towards the end of the list (and their indices incremented
* by one).
* If the attribute values are unordered and already have <tt>attrVal</tt>,
* <tt>IllegalStateException</tt> is thrown.
*
* @param ix The index in the ordered list of attribute values to add the new value.
* 0 <= <tt>ix</tt> <= <tt>size()</tt>.
* @param attrVal The possibly null attribute value to add; if null, null is
* the value added.
* @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
* @exception IllegalStateException If the attribute values are unordered and
* <tt>attrVal</tt> is one of those values.
*/
void add(int ix, Object attrVal);
/** {@collect.stats}
* Sets an attribute value in the ordered list of attribute values.
* This method sets the value at the <tt>ix</tt> index of the list of
* attribute values to be <tt>attrVal</tt>. The old value is removed.
* If the attribute values are unordered,
* this method sets the value that happens to be at that index
* to <tt>attrVal</tt>, unless <tt>attrVal</tt> is already one of the values.
* In that case, <tt>IllegalStateException</tt> is thrown.
*
* @param ix The index of the value in the ordered list of attribute values.
* 0 <= <tt>ix</tt> < <tt>size()</tt>.
* @param attrVal The possibly null attribute value to use.
* If null, 'null' replaces the old value.
* @return The possibly null attribute value at index ix that was replaced.
* Null if the attribute value was null.
* @exception IndexOutOfBoundsException If <tt>ix</tt> is outside the specified range.
* @exception IllegalStateException If <tt>attrVal</tt> already exists and the
* attribute values are unordered.
*/
Object set(int ix, Object attrVal);
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability.
*/
static final long serialVersionUID = 8707690322213556804L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.Binding;
/** {@collect.stats}
* This class represents an item in the NamingEnumeration returned as a
* result of the DirContext.search() methods.
*<p>
* A SearchResult instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single SearchResult instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirContext#search
* @since 1.3
*/
public class SearchResult extends Binding {
/** {@collect.stats}
* Contains the attributes returned with the object.
* @serial
*/
private Attributes attrs;
/** {@collect.stats}
* Constructs a search result using the result's name, its bound object, and
* its attributes.
*<p>
* <tt>getClassName()</tt> will return the class name of <tt>obj</tt>
* (or null if <tt>obj</tt> is null) unless the class name has been
* explicitly set using <tt>setClassName()</tt>.
*
* @param name The non-null name of the search item. It is relative
* to the <em>target context</em> of the search (which is
* named by the first parameter of the <code>search()</code> method)
*
* @param obj The object bound to name. Can be null.
* @param attrs The attributes that were requested to be returned with
* this search item. Cannot be null.
* @see javax.naming.NameClassPair#setClassName
* @see javax.naming.NameClassPair#getClassName
*/
public SearchResult(String name, Object obj, Attributes attrs) {
super(name, obj);
this.attrs = attrs;
}
/** {@collect.stats}
* Constructs a search result using the result's name, its bound object, and
* its attributes, and whether the name is relative.
*<p>
* <tt>getClassName()</tt> will return the class name of <tt>obj</tt>
* (or null if <tt>obj</tt> is null) unless the class name has been
* explicitly set using <tt>setClassName()</tt>
*
* @param name The non-null name of the search item.
* @param obj The object bound to name. Can be null.
* @param attrs The attributes that were requested to be returned with
* this search item. Cannot be null.
* @param isRelative true if <code>name</code> is relative
* to the target context of the search (which is named by
* the first parameter of the <code>search()</code> method);
* false if <code>name</code> is a URL string.
* @see javax.naming.NameClassPair#setClassName
* @see javax.naming.NameClassPair#getClassName
*/
public SearchResult(String name, Object obj, Attributes attrs,
boolean isRelative) {
super(name, obj, isRelative);
this.attrs = attrs;
}
/** {@collect.stats}
* Constructs a search result using the result's name, its class name,
* its bound object, and its attributes.
*
* @param name The non-null name of the search item. It is relative
* to the <em>target context</em> of the search (which is
* named by the first parameter of the <code>search()</code> method)
*
* @param className The possibly null class name of the object
* bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
* returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also null,
* <tt>getClassName()</tt> will return null.
* @param obj The object bound to name. Can be null.
* @param attrs The attributes that were requested to be returned with
* this search item. Cannot be null.
* @see javax.naming.NameClassPair#setClassName
* @see javax.naming.NameClassPair#getClassName
*/
public SearchResult(String name, String className,
Object obj, Attributes attrs) {
super(name, className, obj);
this.attrs = attrs;
}
/** {@collect.stats}
* Constructs a search result using the result's name, its class name,
* its bound object, its attributes, and whether the name is relative.
*
* @param name The non-null name of the search item.
* @param className The possibly null class name of the object
* bound to <tt>name</tt>. If null, the class name of <tt>obj</tt> is
* returned by <tt>getClassName()</tt>. If <tt>obj</tt> is also null,
* <tt>getClassName()</tt> will return null.
* @param obj The object bound to name. Can be null.
* @param attrs The attributes that were requested to be returned with
* this search item. Cannot be null.
* @param isRelative true if <code>name</code> is relative
* to the target context of the search (which is named by
* the first parameter of the <code>search()</code> method);
* false if <code>name</code> is a URL string.
* @see javax.naming.NameClassPair#setClassName
* @see javax.naming.NameClassPair#getClassName
*/
public SearchResult(String name, String className, Object obj,
Attributes attrs, boolean isRelative) {
super(name, className, obj, isRelative);
this.attrs = attrs;
}
/** {@collect.stats}
* Retrieves the attributes in this search result.
*
* @return The non-null attributes in this search result. Can be empty.
* @see #setAttributes
*/
public Attributes getAttributes() {
return attrs;
}
/** {@collect.stats}
* Sets the attributes of this search result to <code>attrs</code>.
* @param attrs The non-null attributes to use. Can be empty.
* @see #getAttributes
*/
public void setAttributes(Attributes attrs) {
this.attrs = attrs;
// ??? check for null?
}
/** {@collect.stats}
* Generates the string representation of this SearchResult.
* The string representation consists of the string representation
* of the binding and the string representation of
* this search result's attributes, separated by ':'.
* The contents of this string is useful
* for debugging and is not meant to be interpreted programmatically.
*
* @return The string representation of this SearchResult. Cannot be null.
*/
public String toString() {
return super.toString() + ":" + getAttributes();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -9158063327699723172L;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
/** {@collect.stats}
* This class provides a basic implementation
* of the Attributes interface.
*<p>
* BasicAttributes is either case-sensitive or case-insensitive (case-ignore).
* This property is determined at the time the BasicAttributes constructor
* is called.
* In a case-insensitive BasicAttributes, the case of its attribute identifiers
* is ignored when searching for an attribute, or adding attributes.
* In a case-sensitive BasicAttributes, the case is significant.
*<p>
* When the BasicAttributes class needs to create an Attribute, it
* uses BasicAttribute. There is no other dependency on BasicAttribute.
*<p>
* Note that updates to BasicAttributes (such as adding or removing an attribute)
* does not affect the corresponding representation in the directory.
* Updates to the directory can only be effected
* using operations in the DirContext interface.
*<p>
* A BasicAttributes instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single BasicAttributes instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirContext#getAttributes
* @see DirContext#modifyAttributes
* @see DirContext#bind
* @see DirContext#rebind
* @see DirContext#createSubcontext
* @see DirContext#search
* @since 1.3
*/
public class BasicAttributes implements Attributes {
/** {@collect.stats}
* Indicates whether case of attribute ids is ignored.
* @serial
*/
private boolean ignoreCase = false;
// The 'key' in attrs is stored in the 'right case'.
// If ignoreCase is true, key is aways lowercase.
// If ignoreCase is false, key is stored as supplied by put().
// %%% Not declared "private" due to bug 4064984.
transient Hashtable attrs = new Hashtable(11);
/** {@collect.stats}
* Constructs a new instance of Attributes.
* The character case of attribute identifiers
* is significant when subsequently retrieving or adding attributes.
*/
public BasicAttributes() {
}
/** {@collect.stats}
* Constructs a new instance of Attributes.
* If <code>ignoreCase</code> is true, the character case of attribute
* identifiers is ignored; otherwise the case is significant.
* @param ignoreCase true means this attribute set will ignore
* the case of its attribute identifiers
* when retrieving or adding attributes;
* false means case is respected.
*/
public BasicAttributes(boolean ignoreCase) {
this.ignoreCase = ignoreCase;
}
/** {@collect.stats}
* Constructs a new instance of Attributes with one attribute.
* The attribute specified by attrID and val are added to the newly
* created attribute.
* The character case of attribute identifiers
* is significant when subsequently retrieving or adding attributes.
* @param attrID non-null The id of the attribute to add.
* @param val The value of the attribute to add. If null, a null
* value is added to the attribute.
*/
public BasicAttributes(String attrID, Object val) {
this();
this.put(new BasicAttribute(attrID, val));
}
/** {@collect.stats}
* Constructs a new instance of Attributes with one attribute.
* The attribute specified by attrID and val are added to the newly
* created attribute.
* If <code>ignoreCase</code> is true, the character case of attribute
* identifiers is ignored; otherwise the case is significant.
* @param attrID non-null The id of the attribute to add.
* If this attribute set ignores the character
* case of its attribute ids, the case of attrID
* is ignored.
* @param val The value of the attribute to add. If null, a null
* value is added to the attribute.
* @param ignoreCase true means this attribute set will ignore
* the case of its attribute identifiers
* when retrieving or adding attributes;
* false means case is respected.
*/
public BasicAttributes(String attrID, Object val, boolean ignoreCase) {
this(ignoreCase);
this.put(new BasicAttribute(attrID, val));
}
public Object clone() {
BasicAttributes attrset;
try {
attrset = (BasicAttributes)super.clone();
} catch (CloneNotSupportedException e) {
attrset = new BasicAttributes(ignoreCase);
}
attrset.attrs = (Hashtable)attrs.clone();
return attrset;
}
public boolean isCaseIgnored() {
return ignoreCase;
}
public int size() {
return attrs.size();
}
public Attribute get(String attrID) {
Attribute attr = (Attribute) attrs.get(
ignoreCase ? attrID.toLowerCase() : attrID);
return (attr);
}
public NamingEnumeration<Attribute> getAll() {
return new AttrEnumImpl();
}
public NamingEnumeration<String> getIDs() {
return new IDEnumImpl();
}
public Attribute put(String attrID, Object val) {
return this.put(new BasicAttribute(attrID, val));
}
public Attribute put(Attribute attr) {
String id = attr.getID();
if (ignoreCase) {
id = id.toLowerCase();
}
return (Attribute)attrs.put(id, attr);
}
public Attribute remove(String attrID) {
String id = (ignoreCase ? attrID.toLowerCase() : attrID);
return (Attribute)attrs.remove(id);
}
/** {@collect.stats}
* Generates the string representation of this attribute set.
* The string consists of each attribute identifier and the contents
* of each attribute. The contents of this string is useful
* for debugging and is not meant to be interpreted programmatically.
*
* @return A non-null string listing the contents of this attribute set.
*/
public String toString() {
if (attrs.size() == 0) {
return("No attributes");
} else {
return attrs.toString();
}
}
/** {@collect.stats}
* Determines whether this <tt>BasicAttributes</tt> is equal to another
* <tt>Attributes</tt>
* Two <tt>Attributes</tt> are equal if they are both instances of
* <tt>Attributes</tt>,
* treat the case of attribute IDs the same way, and contain the
* same attributes. Each <tt>Attribute</tt> in this <tt>BasicAttributes</tt>
* is checked for equality using <tt>Object.equals()</tt>, which may have
* be overridden by implementations of <tt>Attribute</tt>).
* If a subclass overrides <tt>equals()</tt>,
* it should override <tt>hashCode()</tt>
* as well so that two <tt>Attributes</tt> instances that are equal
* have the same hash code.
* @param obj the possibly null object to compare against.
*
* @return true If obj is equal to this BasicAttributes.
* @see #hashCode
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof Attributes)) {
Attributes target = (Attributes)obj;
// Check case first
if (ignoreCase != target.isCaseIgnored()) {
return false;
}
if (size() == target.size()) {
Attribute their, mine;
try {
NamingEnumeration theirs = target.getAll();
while (theirs.hasMore()) {
their = (Attribute)theirs.next();
mine = get(their.getID());
if (!their.equals(mine)) {
return false;
}
}
} catch (NamingException e) {
return false;
}
return true;
}
}
return false;
}
/** {@collect.stats}
* Calculates the hash code of this BasicAttributes.
*<p>
* The hash code is computed by adding the hash code of
* the attributes of this object. If this BasicAttributes
* ignores case of its attribute IDs, one is added to the hash code.
* If a subclass overrides <tt>hashCode()</tt>,
* it should override <tt>equals()</tt>
* as well so that two <tt>Attributes</tt> instances that are equal
* have the same hash code.
*
* @return an int representing the hash code of this BasicAttributes instance.
* @see #equals
*/
public int hashCode() {
int hash = (ignoreCase ? 1 : 0);
try {
NamingEnumeration all = getAll();
while (all.hasMore()) {
hash += all.next().hashCode();
}
} catch (NamingException e) {}
return hash;
}
/** {@collect.stats}
* Overridden to avoid exposing implementation details.
* @serialData Default field (ignoreCase flag -- a boolean), followed by
* the number of attributes in the set
* (an int), and then the individual Attribute objects.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject(); // write out the ignoreCase flag
s.writeInt(attrs.size());
Enumeration attrEnum = attrs.elements();
while (attrEnum.hasMoreElements()) {
s.writeObject(attrEnum.nextElement());
}
}
/** {@collect.stats}
* Overridden to avoid exposing implementation details.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject(); // read in the ignoreCase flag
int n = s.readInt(); // number of attributes
attrs = (n >= 1)
? new Hashtable(n * 2)
: new Hashtable(2); // can't have initial size of 0 (grrr...)
while (--n >= 0) {
put((Attribute)s.readObject());
}
}
class AttrEnumImpl implements NamingEnumeration<Attribute> {
Enumeration<Attribute> elements;
public AttrEnumImpl() {
this.elements = attrs.elements();
}
public boolean hasMoreElements() {
return elements.hasMoreElements();
}
public Attribute nextElement() {
return elements.nextElement();
}
public boolean hasMore() throws NamingException {
return hasMoreElements();
}
public Attribute next() throws NamingException {
return nextElement();
}
public void close() throws NamingException {
elements = null;
}
}
class IDEnumImpl implements NamingEnumeration<String> {
Enumeration<Attribute> elements;
public IDEnumImpl() {
// Walking through the elements, rather than the keys, gives
// us attribute IDs that have not been converted to lowercase.
this.elements = attrs.elements();
}
public boolean hasMoreElements() {
return elements.hasMoreElements();
}
public String nextElement() {
Attribute attr = elements.nextElement();
return attr.getID();
}
public boolean hasMore() throws NamingException {
return hasMoreElements();
}
public String next() throws NamingException {
return nextElement();
}
public void close() throws NamingException {
elements = null;
}
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability.
*/
private static final long serialVersionUID = 4980164073184639448L;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import java.util.Vector;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import javax.naming.OperationNotSupportedException;
/** {@collect.stats}
* This class provides a basic implementation of the <tt>Attribute</tt> interface.
*<p>
* This implementation does not support the schema methods
* <tt>getAttributeDefinition()</tt> and <tt>getAttributeSyntaxDefinition()</tt>.
* They simply throw <tt>OperationNotSupportedException</tt>.
* Subclasses of <tt>BasicAttribute</tt> should override these methods if they
* support them.
*<p>
* The <tt>BasicAttribute</tt> class by default uses <tt>Object.equals()</tt> to
* determine equality of attribute values when testing for equality or
* when searching for values, <em>except</em> when the value is an array.
* For an array, each element of the array is checked using <tt>Object.equals()</tt>.
* Subclasses of <tt>BasicAttribute</tt> can make use of schema information
* when doing similar equality checks by overriding methods
* in which such use of schema is meaningful.
* Similarly, the <tt>BasicAttribute</tt> class by default returns the values passed to its
* constructor and/or manipulated using the add/remove methods.
* Subclasses of <tt>BasicAttribute</tt> can override <tt>get()</tt> and <tt>getAll()</tt>
* to get the values dynamically from the directory (or implement
* the <tt>Attribute</tt> interface directly instead of subclassing <tt>BasicAttribute</tt>).
*<p>
* Note that updates to <tt>BasicAttribute</tt> (such as adding or removing a value)
* does not affect the corresponding representation of the attribute
* in the directory. Updates to the directory can only be effected
* using operations in the <tt>DirContext</tt> interface.
*<p>
* A <tt>BasicAttribute</tt> instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify a
* <tt>BasicAttribute</tt> should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class BasicAttribute implements Attribute {
/** {@collect.stats}
* Holds the attribute's id. It is initialized by the public constructor and
* cannot be null unless methods in BasicAttribute that use attrID
* have been overridden.
* @serial
*/
protected String attrID;
/** {@collect.stats}
* Holds the attribute's values. Initialized by public constructors.
* Cannot be null unless methods in BasicAttribute that use
* values have been overridden.
*/
protected transient Vector<Object> values;
/** {@collect.stats}
* A flag for recording whether this attribute's values are ordered.
* @serial
*/
protected boolean ordered = false;
public Object clone() {
BasicAttribute attr;
try {
attr = (BasicAttribute)super.clone();
} catch (CloneNotSupportedException e) {
attr = new BasicAttribute(attrID, ordered);
}
attr.values = (Vector)values.clone();
return attr;
}
/** {@collect.stats}
* Determines whether obj is equal to this attribute.
* Two attributes are equal if their attribute-ids, syntaxes
* and values are equal.
* If the attribute values are unordered, the order that the values were added
* are irrelevant. If the attribute values are ordered, then the
* order the values must match.
* If obj is null or not an Attribute, false is returned.
*<p>
* By default <tt>Object.equals()</tt> is used when comparing the attribute
* id and its values except when a value is an array. For an array,
* each element of the array is checked using <tt>Object.equals()</tt>.
* A subclass may override this to make
* use of schema syntax information and matching rules,
* which define what it means for two attributes to be equal.
* How and whether a subclass makes
* use of the schema information is determined by the subclass.
* If a subclass overrides <tt>equals()</tt>, it should also override
* <tt>hashCode()</tt>
* such that two attributes that are equal have the same hash code.
*
* @param obj The possibly null object to check.
* @return true if obj is equal to this attribute; false otherwise.
* @see #hashCode
* @see #contains
*/
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof Attribute)) {
Attribute target = (Attribute)obj;
// Check order first
if (isOrdered() != target.isOrdered()) {
return false;
}
int len;
if (attrID.equals(target.getID()) &&
(len=size()) == target.size()) {
try {
if (isOrdered()) {
// Go through both list of values
for (int i = 0; i < len; i++) {
if (!valueEquals(get(i), target.get(i))) {
return false;
}
}
} else {
// order is not relevant; check for existence
Enumeration theirs = target.getAll();
while (theirs.hasMoreElements()) {
if (find(theirs.nextElement()) < 0)
return false;
}
}
} catch (NamingException e) {
return false;
}
return true;
}
}
return false;
}
/** {@collect.stats}
* Calculates the hash code of this attribute.
*<p>
* The hash code is computed by adding the hash code of
* the attribute's id and that of all of its values except for
* values that are arrays.
* For an array, the hash code of each element of the array is summed.
* If a subclass overrides <tt>hashCode()</tt>, it should override
* <tt>equals()</tt>
* as well so that two attributes that are equal have the same hash code.
*
* @return an int representing the hash code of this attribute.
* @see #equals
*/
public int hashCode() {
int hash = attrID.hashCode();
int num = values.size();
Object val;
for (int i = 0; i < num; i ++) {
val = values.elementAt(i);
if (val != null) {
if (val.getClass().isArray()) {
Object it;
int len = Array.getLength(val);
for (int j = 0 ; j < len ; j++) {
it = Array.get(val, j);
if (it != null) {
hash += it.hashCode();
}
}
} else {
hash += val.hashCode();
}
}
}
return hash;
}
/** {@collect.stats}
* Generates the string representation of this attribute.
* The string consists of the attribute's id and its values.
* This string is meant for debugging and not meant to be
* interpreted programmatically.
* @return The non-null string representation of this attribute.
*/
public String toString() {
StringBuffer answer = new StringBuffer(attrID + ": ");
if (values.size() == 0) {
answer.append("No values");
} else {
boolean start = true;
for (Enumeration e = values.elements(); e.hasMoreElements(); ) {
if (!start)
answer.append(", ");
answer.append(e.nextElement());
start = false;
}
}
return answer.toString();
}
/** {@collect.stats}
* Constructs a new instance of an unordered attribute with no value.
*
* @param id The attribute's id. It cannot be null.
*/
public BasicAttribute(String id) {
this(id, false);
}
/** {@collect.stats}
* Constructs a new instance of an unordered attribute with a single value.
*
* @param id The attribute's id. It cannot be null.
* @param value The attribute's value. If null, a null
* value is added to the attribute.
*/
public BasicAttribute(String id, Object value) {
this(id, value, false);
}
/** {@collect.stats}
* Constructs a new instance of a possibly ordered attribute with no value.
*
* @param id The attribute's id. It cannot be null.
* @param ordered true means the attribute's values will be ordered;
* false otherwise.
*/
public BasicAttribute(String id, boolean ordered) {
attrID = id;
values = new Vector();
this.ordered = ordered;
}
/** {@collect.stats}
* Constructs a new instance of a possibly ordered attribute with a
* single value.
*
* @param id The attribute's id. It cannot be null.
* @param value The attribute's value. If null, a null
* value is added to the attribute.
* @param ordered true means the attribute's values will be ordered;
* false otherwise.
*/
public BasicAttribute(String id, Object value, boolean ordered) {
this(id, ordered);
values.addElement(value);
}
/** {@collect.stats}
* Retrieves an enumeration of this attribute's values.
*<p>
* By default, the values returned are those passed to the
* constructor and/or manipulated using the add/replace/remove methods.
* A subclass may override this to retrieve the values dynamically
* from the directory.
*/
public NamingEnumeration<?> getAll() throws NamingException {
return new ValuesEnumImpl();
}
/** {@collect.stats}
* Retrieves one of this attribute's values.
*<p>
* By default, the value returned is one of those passed to the
* constructor and/or manipulated using the add/replace/remove methods.
* A subclass may override this to retrieve the value dynamically
* from the directory.
*/
public Object get() throws NamingException {
if (values.size() == 0) {
throw new
NoSuchElementException("Attribute " + getID() + " has no value");
} else {
return values.elementAt(0);
}
}
public int size() {
return values.size();
}
public String getID() {
return attrID;
}
/** {@collect.stats}
* Determines whether a value is in this attribute.
*<p>
* By default,
* <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
* with this attribute's values except when <tt>attrVal</tt> is an array.
* For an array, each element of the array is checked using
* <tt>Object.equals()</tt>.
* A subclass may use schema information to determine equality.
*/
public boolean contains(Object attrVal) {
return (find(attrVal) >= 0);
}
// For finding first element that has a null in JDK1.1 Vector.
// In the Java 2 platform, can just replace this with Vector.indexOf(target);
private int find(Object target) {
Class cl;
if (target == null) {
int ct = values.size();
for (int i = 0 ; i < ct ; i++) {
if (values.elementAt(i) == null)
return i;
}
} else if ((cl=target.getClass()).isArray()) {
int ct = values.size();
Object it;
for (int i = 0 ; i < ct ; i++) {
it = values.elementAt(i);
if (it != null && cl == it.getClass()
&& arrayEquals(target, it))
return i;
}
} else {
return values.indexOf(target, 0);
}
return -1; // not found
}
/** {@collect.stats}
* Determines whether two attribute values are equal.
* Use arrayEquals for arrays and <tt>Object.equals()</tt> otherwise.
*/
private static boolean valueEquals(Object obj1, Object obj2) {
if (obj1 == obj2) {
return true; // object references are equal
}
if (obj1 == null) {
return false; // obj2 was not false
}
if (obj1.getClass().isArray() &&
obj2.getClass().isArray()) {
return arrayEquals(obj1, obj2);
}
return (obj1.equals(obj2));
}
/** {@collect.stats}
* Determines whether two arrays are equal by comparing each of their
* elements using <tt>Object.equals()</tt>.
*/
private static boolean arrayEquals(Object a1, Object a2) {
int len;
if ((len = Array.getLength(a1)) != Array.getLength(a2))
return false;
for (int j = 0; j < len; j++) {
Object i1 = Array.get(a1, j);
Object i2 = Array.get(a2, j);
if (i1 == null || i2 == null) {
if (i1 != i2)
return false;
} else if (!i1.equals(i2)) {
return false;
}
}
return true;
}
/** {@collect.stats}
* Adds a new value to this attribute.
*<p>
* By default, <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
* with this attribute's values except when <tt>attrVal</tt> is an array.
* For an array, each element of the array is checked using
* <tt>Object.equals()</tt>.
* A subclass may use schema information to determine equality.
*/
public boolean add(Object attrVal) {
if (isOrdered() || (find(attrVal) < 0)) {
values.addElement(attrVal);
return true;
} else {
return false;
}
}
/** {@collect.stats}
* Removes a specified value from this attribute.
*<p>
* By default, <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
* with this attribute's values except when <tt>attrVal</tt> is an array.
* For an array, each element of the array is checked using
* <tt>Object.equals()</tt>.
* A subclass may use schema information to determine equality.
*/
public boolean remove(Object attrval) {
// For the Java 2 platform, can just use "return removeElement(attrval);"
// Need to do the following to handle null case
int i = find(attrval);
if (i >= 0) {
values.removeElementAt(i);
return true;
}
return false;
}
public void clear() {
values.setSize(0);
}
// ---- ordering methods
public boolean isOrdered() {
return ordered;
}
public Object get(int ix) throws NamingException {
return values.elementAt(ix);
}
public Object remove(int ix) {
Object answer = values.elementAt(ix);
values.removeElementAt(ix);
return answer;
}
public void add(int ix, Object attrVal) {
if (!isOrdered() && contains(attrVal)) {
throw new IllegalStateException(
"Cannot add duplicate to unordered attribute");
}
values.insertElementAt(attrVal, ix);
}
public Object set(int ix, Object attrVal) {
if (!isOrdered() && contains(attrVal)) {
throw new IllegalStateException(
"Cannot add duplicate to unordered attribute");
}
Object answer = values.elementAt(ix);
values.setElementAt(attrVal, ix);
return answer;
}
// ----------------- Schema methods
/** {@collect.stats}
* Retrieves the syntax definition associated with this attribute.
*<p>
* This method by default throws OperationNotSupportedException. A subclass
* should override this method if it supports schema.
*/
public DirContext getAttributeSyntaxDefinition() throws NamingException {
throw new OperationNotSupportedException("attribute syntax");
}
/** {@collect.stats}
* Retrieves this attribute's schema definition.
*<p>
* This method by default throws OperationNotSupportedException. A subclass
* should override this method if it supports schema.
*/
public DirContext getAttributeDefinition() throws NamingException {
throw new OperationNotSupportedException("attribute definition");
}
// ---- serialization methods
/** {@collect.stats}
* Overridden to avoid exposing implementation details
* @serialData Default field (the attribute ID -- a String),
* followed by the number of values (an int), and the
* individual values.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject(); // write out the attrID
s.writeInt(values.size());
for (int i = 0; i < values.size(); i++) {
s.writeObject(values.elementAt(i));
}
}
/** {@collect.stats}
* Overridden to avoid exposing implementation details.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject(); // read in the attrID
int n = s.readInt(); // number of values
values = new Vector(n);
while (--n >= 0) {
values.addElement(s.readObject());
}
}
class ValuesEnumImpl implements NamingEnumeration<Object> {
Enumeration list;
ValuesEnumImpl() {
list = values.elements();
}
public boolean hasMoreElements() {
return list.hasMoreElements();
}
public Object nextElement() {
return(list.nextElement());
}
public Object next() throws NamingException {
return list.nextElement();
}
public boolean hasMore() throws NamingException {
return list.hasMoreElements();
}
public void close() throws NamingException {
list = null;
}
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability.
*/
private static final long serialVersionUID = 6743528196119291326L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when a method
* in some ways violates the schema. An example of schema violation
* is modifying attributes of an object that violates the object's
* schema definition. Another example is renaming or moving an object
* to a part of the namespace that violates the namespace's
* schema definition.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see javax.naming.Context#bind
* @see DirContext#bind
* @see javax.naming.Context#rebind
* @see DirContext#rebind
* @see DirContext#createSubcontext
* @see javax.naming.Context#createSubcontext
* @see DirContext#modifyAttributes
* @since 1.3
*/
public class SchemaViolationException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of SchemaViolationException.
* All fields are set to null.
*/
public SchemaViolationException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of SchemaViolationException
* using the explanation supplied. All other fields are set to null.
* @param explanation Detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public SchemaViolationException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3041762429525049663L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when the specification of
* a search filter is invalid. The expression of the filter may
* be invalid, or there may be a problem with one of the parameters
* passed to the filter.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidSearchFilterException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InvalidSearchFilterException.
* All fields are set to null.
*/
public InvalidSearchFilterException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of InvalidSearchFilterException
* with an explanation. All other fields are set to null.
* @param msg Detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public InvalidSearchFilterException(String msg) {
super(msg);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 2902700940682875441L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
/** {@collect.stats}
* This class encapsulates
* factors that determine scope of search and what gets returned
* as a result of the search.
*<p>
* A SearchControls instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single SearchControls instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class SearchControls implements java.io.Serializable {
/** {@collect.stats}
* Search the named object.
*<p>
* The NamingEnumeration that results from search()
* using OBJECT_SCOPE will contain one or zero element.
* The enumeration contains one element if the named object satisfies
* the search filter specified in search().
* The element will have as its name the empty string because the names
* of elements in the NamingEnumeration are relative to the
* target context--in this case, the target context is the named object.
* It contains zero element if the named object does not satisfy
* the search filter specified in search().
* <p>
* The value of this constant is <tt>0</tt>.
*/
public final static int OBJECT_SCOPE = 0;
/** {@collect.stats}
* Search one level of the named context.
*<p>
* The NamingEnumeration that results from search()
* using ONELEVEL_SCOPE contains elements with
* objects in the named context that satisfy
* the search filter specified in search().
* The names of elements in the NamingEnumeration are atomic names
* relative to the named context.
* <p>
* The value of this constant is <tt>1</tt>.
*/
public final static int ONELEVEL_SCOPE = 1;
/** {@collect.stats}
* Search the entire subtree rooted at the named object.
*<p>
* If the named object is not a DirContext, search only the object.
* If the named object is a DirContext, search the subtree
* rooted at the named object, including the named object itself.
*<p>
* The search will not cross naming system boundaries.
*<p>
* The NamingEnumeration that results from search()
* using SUBTREE_SCOPE contains elements of objects
* from the subtree (including the named context)
* that satisfy the search filter specified in search().
* The names of elements in the NamingEnumeration are either
* relative to the named context or is a URL string.
* If the named context satisfies the search filter, it is
* included in the enumeration with the empty string as
* its name.
* <p>
* The value of this constant is <tt>2</tt>.
*/
public final static int SUBTREE_SCOPE = 2;
/** {@collect.stats}
* Contains the scope with which to apply the search. One of
* <tt>ONELEVEL_SCOPE</tt>, <tt>OBJECT_SCOPE</tt>, or
* <tt>SUBTREE_SCOPE</tt>.
* @serial
*/
private int searchScope;
/** {@collect.stats}
* Contains the milliseconds to wait before returning
* from search.
* @serial
*/
private int timeLimit;
/** {@collect.stats}
* Indicates whether JNDI links are dereferenced during
* search.
* @serial
*/
private boolean derefLink;
/** {@collect.stats}
* Indicates whether object is returned in <tt>SearchResult</tt>.
* @serial
*/
private boolean returnObj;
/** {@collect.stats}
* Contains the maximum number of SearchResults to return.
* @serial
*/
private long countLimit;
/** {@collect.stats}
* Contains the list of attributes to be returned in
* <tt>SearchResult</tt> for each matching entry of search. <tt>null</tt>
* indicates that all attributes are to be returned.
* @serial
*/
private String[] attributesToReturn;
/** {@collect.stats}
* Constructs a search constraints using defaults.
*<p>
* The defaults are:
* <ul>
* <li>search one level
* <li>no maximum return limit for search results
* <li>no time limit for search
* <li>return all attributes associated with objects that satisfy
* the search filter.
* <li>do not return named object (return only name and class)
* <li>do not dereference links during search
*</ul>
*/
public SearchControls() {
searchScope = ONELEVEL_SCOPE;
timeLimit = 0; // no limit
countLimit = 0; // no limit
derefLink = false;
returnObj = false;
attributesToReturn = null; // return all
}
/** {@collect.stats}
* Constructs a search constraints using arguments.
* @param scope The search scope. One of:
* OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.
* @param timelim The number of milliseconds to wait before returning.
* If 0, wait indefinitely.
* @param deref If true, dereference links during search.
* @param countlim The maximum number of entries to return. If 0, return
* all entries that satisfy filter.
* @param retobj If true, return the object bound to the name of the
* entry; if false, do not return object.
* @param attrs The identifiers of the attributes to return along with
* the entry. If null, return all attributes. If empty
* return no attributes.
*/
public SearchControls(int scope,
long countlim,
int timelim,
String[] attrs,
boolean retobj,
boolean deref) {
searchScope = scope;
timeLimit = timelim; // no limit
derefLink = deref;
returnObj = retobj;
countLimit = countlim; // no limit
attributesToReturn = attrs; // return all
}
/** {@collect.stats}
* Retrieves the search scope of these SearchControls.
*<p>
* One of OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.
*
* @return The search scope of this SearchControls.
* @see #setSearchScope
*/
public int getSearchScope() {
return searchScope;
}
/** {@collect.stats}
* Retrieves the time limit of these SearchControls in milliseconds.
*<p>
* If the value is 0, this means to wait indefinitely.
* @return The time limit of these SearchControls in milliseconds.
* @see #setTimeLimit
*/
public int getTimeLimit() {
return timeLimit;
}
/** {@collect.stats}
* Determines whether links will be dereferenced during the search.
*
* @return true if links will be dereferenced; false otherwise.
* @see #setDerefLinkFlag
*/
public boolean getDerefLinkFlag() {
return derefLink;
}
/** {@collect.stats}
* Determines whether objects will be returned as part of the result.
*
* @return true if objects will be returned; false otherwise.
* @see #setReturningObjFlag
*/
public boolean getReturningObjFlag() {
return returnObj;
}
/** {@collect.stats}
* Retrieves the maximum number of entries that will be returned
* as a result of the search.
*<p>
* 0 indicates that all entries will be returned.
* @return The maximum number of entries that will be returned.
* @see #setCountLimit
*/
public long getCountLimit() {
return countLimit;
}
/** {@collect.stats}
* Retrieves the attributes that will be returned as part of the search.
*<p>
* A value of null indicates that all attributes will be returned.
* An empty array indicates that no attributes are to be returned.
*
* @return An array of attribute ids identifying the attributes that
* will be returned. Can be null.
* @see #setReturningAttributes
*/
public String[] getReturningAttributes() {
return attributesToReturn;
}
/** {@collect.stats}
* Sets the search scope to one of:
* OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.
* @param scope The search scope of this SearchControls.
* @see #getSearchScope
*/
public void setSearchScope(int scope) {
searchScope = scope;
}
/** {@collect.stats}
* Sets the time limit of these SearchControls in milliseconds.
*<p>
* If the value is 0, this means to wait indefinitely.
* @param ms The time limit of these SearchControls in milliseconds.
* @see #getTimeLimit
*/
public void setTimeLimit(int ms) {
timeLimit = ms;
}
/** {@collect.stats}
* Enables/disables link dereferencing during the search.
*
* @param on if true links will be dereferenced; if false, not followed.
* @see #getDerefLinkFlag
*/
public void setDerefLinkFlag(boolean on) {
derefLink = on;
}
/** {@collect.stats}
* Enables/disables returning objects returned as part of the result.
*<p>
* If disabled, only the name and class of the object is returned.
* If enabled, the object will be returned.
*
* @param on if true, objects will be returned; if false,
* objects will not be returned.
* @see #getReturningObjFlag
*/
public void setReturningObjFlag(boolean on) {
returnObj = on;
}
/** {@collect.stats}
* Sets the maximum number of entries to be returned
* as a result of the search.
*<p>
* 0 indicates no limit: all entries will be returned.
*
* @param limit The maximum number of entries that will be returned.
* @see #getCountLimit
*/
public void setCountLimit(long limit) {
countLimit = limit;
}
/** {@collect.stats}
* Specifies the attributes that will be returned as part of the search.
*<p>
* null indicates that all attributes will be returned.
* An empty array indicates no attributes are returned.
*
* @param attrs An array of attribute ids identifying the attributes that
* will be returned. Can be null.
* @see #getReturningAttributes
*/
public void setReturningAttributes(String[] attrs) {
attributesToReturn = attrs;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability.
*/
private static final long serialVersionUID = -2480540967773454797L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This class is thrown when an attempt is
* made to add to an attribute a value that conflicts with the attribute's
* schema definition. This could happen, for example, if attempting
* to add an attribute with no value when the attribute is required
* to have at least one value, or if attempting to add more than
* one value to a single valued-attribute, or if attempting to
* add a value that conflicts with the syntax of the attribute.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidAttributeValueException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InvalidAttributeValueException using
* an explanation. All other fields are set to null.
* @param explanation Additional detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public InvalidAttributeValueException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of InvalidAttributeValueException.
* All fields are set to null.
*/
public InvalidAttributeValueException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 8720050295499275011L;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import java.util.Hashtable;
import javax.naming.spi.NamingManager;
import javax.naming.*;
/** {@collect.stats}
* This class is the starting context for performing
* directory operations. The documentation in the class description
* of InitialContext (including those for synchronization) apply here.
*
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see javax.naming.InitialContext
* @since 1.3
*/
public class InitialDirContext extends InitialContext implements DirContext {
/** {@collect.stats}
* Constructs an initial DirContext with the option of not
* initializing it. This may be used by a constructor in
* a subclass when the value of the environment parameter
* is not yet known at the time the <tt>InitialDirContext</tt>
* constructor is called. The subclass's constructor will
* call this constructor, compute the value of the environment,
* and then call <tt>init()</tt> before returning.
*
* @param lazy
* true means do not initialize the initial DirContext; false
* is equivalent to calling <tt>new InitialDirContext()</tt>
* @throws NamingException if a naming exception is encountered
*
* @see InitialContext#init(Hashtable)
* @since 1.3
*/
protected InitialDirContext(boolean lazy) throws NamingException {
super(lazy);
}
/** {@collect.stats}
* Constructs an initial DirContext.
* No environment properties are supplied.
* Equivalent to <tt>new InitialDirContext(null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*
* @see #InitialDirContext(Hashtable)
*/
public InitialDirContext() throws NamingException {
super();
}
/** {@collect.stats}
* Constructs an initial DirContext using the supplied environment.
* Environment properties are discussed in the
* <tt>javax.naming.InitialContext</tt> class description.
*
* <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone.
*
* @param environment
* environment used to create the initial DirContext.
* Null indicates an empty environment.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialDirContext(Hashtable<?,?> environment)
throws NamingException
{
super(environment);
}
private DirContext getURLOrDefaultInitDirCtx(String name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
private DirContext getURLOrDefaultInitDirCtx(Name name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
// DirContext methods
// Most Javadoc is deferred to the DirContext interface.
public Attributes getAttributes(String name)
throws NamingException {
return getAttributes(name, null);
}
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);
}
public Attributes getAttributes(Name name)
throws NamingException {
return getAttributes(name, null);
}
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);
}
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void bind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext getSchema(String name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchema(Name name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchemaClassDefinition(String name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
public DirContext getSchemaClassDefinition(Name name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
// -------------------- search operations
public NamingEnumeration<SearchResult>
search(String name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(Name name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(String name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when attempting to access
* an attribute that does not exist.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NoSuchAttributeException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of NoSuchAttributeException using
* an explanation. All other fields are set to null.
* @param explanation Additional detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public NoSuchAttributeException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NoSuchAttributeException.
* All fields are initialized to null.
*/
public NoSuchAttributeException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 4836415647935888137L;
}
|
Java
|
/*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.*;
/** {@collect.stats}
* The directory service interface, containing
* methods for examining and updating attributes
* associated with objects, and for searching the directory.
* <p>
* <h4>Names</h4>
* Each name passed as an argument to a <tt>DirContext</tt> method is relative
* to that context. The empty name is used to name the context itself.
* The name parameter may never be null.
* <p>
* Most of the methods have overloaded versions with one taking a
* <code>Name</code> parameter and one taking a <code>String</code>.
* These overloaded versions are equivalent in that if
* the <code>Name</code> and <code>String</code> parameters are just
* different representations of the same name, then the overloaded
* versions of the same methods behave the same.
* In the method descriptions below, only one version is documented.
* The second version instead has a link to the first: the same
* documentation applies to both.
* <p>
* See <tt>Context</tt> for a discussion on the interpretation of the
* name argument to the <tt>Context</tt> methods. These same rules
* apply to the name argument to the <tt>DirContext</tt> methods.
* <p>
* <h4>Attribute Models</h4>
* There are two basic models of what attributes should be
* associated with. First, attributes may be directly associated with a
* DirContext object.
* In this model, an attribute operation on the named object is
* roughly equivalent
* to a lookup on the name (which returns the DirContext object),
* followed by the attribute operation invoked on the DirContext object
* in which the caller supplies an empty name. The attributes can be viewed
* as being stored along with the object (note that this does not imply that
* the implementation must do so).
* <p>
* The second model is that attributes are associated with a
* name (typically an atomic name) in a DirContext.
* In this model, an attribute operation on the named object is
* roughly equivalent to a lookup on the name of the parent DirContext of the
* named object, followed by the attribute operation invoked on the parent
* in which the caller supplies the terminal atomic name.
* The attributes can be viewed as being stored in the parent DirContext
* (again, this does not imply that the implementation must do so).
* Objects that are not DirContexts can have attributes, as long as
* their parents are DirContexts.
* <p>
* JNDI support both of these models.
* It is up to the individual service providers to decide where to
* "store" attributes.
* JNDI clients are safest when they do not make assumptions about
* whether an object's attributes are stored as part of the object, or stored
* within the parent object and associated with the object's name.
* <p>
* <h4>Attribute Type Names</h4>
* In the <tt>getAttributes()</tt> and <tt>search()</tt> methods,
* you can supply the attributes to return by supplying a list of
* attribute names (strings).
* The attributes that you get back might not have the same names as the
* attribute names you have specified. This is because some directories
* support features that cause them to return other attributes. Such
* features include attribute subclassing, attribute name synonyms, and
* attribute language codes.
* <p>
* In attribute subclassing, attributes are defined in a class hierarchy.
* In some directories, for example, the "name" attribute might be the
* superclass of all name-related attributes, including "commonName" and
* "surName". Asking for the "name" attribute might return both the
* "commonName" and "surName" attributes.
* <p>
* With attribute type synonyms, a directory can assign multiple names to
* the same attribute. For example, "cn" and "commonName" might both
* refer to the same attribute. Asking for "cn" might return the
* "commonName" attribute.
* <p>
* Some directories support the language codes for attributes.
* Asking such a directory for the "description" attribute, for example,
* might return all of the following attributes:
* <ul>
* <li>description
* <li>description;lang-en
* <li>description;lang-de
* <li>description;lang-fr
* </ul>
*
* <p>
*<h4>Operational Attributes</h4>
*<p>
* Some directories have the notion of "operational attributes" which are
* attributes associated with a directory object for administrative
* purposes. An example of operational attributes is the access control
* list for an object.
* <p>
* In the <tt>getAttributes()</tt> and <tt>search()</tt> methods,
* you can specify that all attributes associated with the requested objects
* be returned by supply <tt>null</tt> as the list of attributes to return.
* The attributes returned do <em>not</em> include operational attributes.
* In order to retrieve operational attributes, you must name them explicitly.
*
* <p>
* <h4>Named Context</h4>
* <p>
* There are certain methods in which the name must resolve to a context
* (for example, when searching a single level context). The documentation
* of such methods
* use the term <em>named context</em> to describe their name parameter.
* For these methods, if the named object is not a DirContext,
* <code>NotContextException</code> is thrown.
* Aside from these methods, there is no requirement that the
* <em>named object</em> be a DirContext.
*<p>
*<h4>Parameters</h4>
*<p>
* An <tt>Attributes</tt>, <tt>SearchControls</tt>, or array object
* passed as a parameter to any method will not be modified by the
* service provider. The service provider may keep a reference to it
* for the duration of the operation, including any enumeration of the
* method's results and the processing of any referrals generated.
* The caller should not modify the object during this time.
* An <tt>Attributes</tt> object returned by any method is owned by
* the caller. The caller may subsequently modify it; the service
* provider will not.
*<p>
*<h4>Exceptions</h4>
*<p>
* All the methods in this interface can throw a NamingException or
* any of its subclasses. See NamingException and their subclasses
* for details on each exception.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author R. Vasudevan
*
* @see javax.naming.Context
* @since 1.3
*/
public interface DirContext extends Context {
/** {@collect.stats}
* Retrieves all of the attributes associated with a named object.
* See the class description regarding attribute models, attribute
* type names, and operational attributes.
*
* @param name
* the name of the object from which to retrieve attributes
* @return the set of attributes associated with <code>name</code>.
* Returns an empty attribute set if name has no attributes;
* never null.
* @throws NamingException if a naming exception is encountered
*
* @see #getAttributes(String)
* @see #getAttributes(Name, String[])
*/
public Attributes getAttributes(Name name) throws NamingException;
/** {@collect.stats}
* Retrieves all of the attributes associated with a named object.
* See {@link #getAttributes(Name)} for details.
*
* @param name
* the name of the object from which to retrieve attributes
* @return the set of attributes associated with <code>name</code>
*
* @throws NamingException if a naming exception is encountered
*/
public Attributes getAttributes(String name) throws NamingException;
/** {@collect.stats}
* Retrieves selected attributes associated with a named object.
* See the class description regarding attribute models, attribute
* type names, and operational attributes.
*
* <p> If the object does not have an attribute
* specified, the directory will ignore the nonexistent attribute
* and return those requested attributes that the object does have.
*
* <p> A directory might return more attributes than was requested
* (see <strong>Attribute Type Names</strong> in the class description),
* but is not allowed to return arbitrary, unrelated attributes.
*
* <p> See also <strong>Operational Attributes</strong> in the class
* description.
*
* @param name
* the name of the object from which to retrieve attributes
* @param attrIds
* the identifiers of the attributes to retrieve.
* null indicates that all attributes should be retrieved;
* an empty array indicates that none should be retrieved.
* @return the requested attributes; never null
*
* @throws NamingException if a naming exception is encountered
*/
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException;
/** {@collect.stats}
* Retrieves selected attributes associated with a named object.
* See {@link #getAttributes(Name, String[])} for details.
*
* @param name
* The name of the object from which to retrieve attributes
* @param attrIds
* the identifiers of the attributes to retrieve.
* null indicates that all attributes should be retrieved;
* an empty array indicates that none should be retrieved.
* @return the requested attributes; never null
*
* @throws NamingException if a naming exception is encountered
*/
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException;
/** {@collect.stats}
* This constant specifies to add an attribute with the specified values.
* <p>
* If attribute does not exist,
* create the attribute. The resulting attribute has a union of the
* specified value set and the prior value set.
* Adding an attribute with no value will throw
* <code>InvalidAttributeValueException</code> if the attribute must have
* at least one value. For a single-valued attribute where that attribute
* already exists, throws <code>AttributeInUseException</code>.
* If attempting to add more than one value to a single-valued attribute,
* throws <code>InvalidAttributeValueException</code>.
* <p>
* The value of this constant is <tt>1</tt>.
*
* @see ModificationItem
* @see #modifyAttributes
*/
public final static int ADD_ATTRIBUTE = 1;
/** {@collect.stats}
* This constant specifies to replace an attribute with specified values.
*<p>
* If attribute already exists,
* replaces all existing values with new specified values. If the
* attribute does not exist, creates it. If no value is specified,
* deletes all the values of the attribute.
* Removal of the last value will remove the attribute if the attribute
* is required to have at least one value. If
* attempting to add more than one value to a single-valued attribute,
* throws <code>InvalidAttributeValueException</code>.
* <p>
* The value of this constant is <tt>2</tt>.
*
* @see ModificationItem
* @see #modifyAttributes
*/
public final static int REPLACE_ATTRIBUTE = 2;
/** {@collect.stats}
* This constant specifies to delete
* the specified attribute values from the attribute.
*<p>
* The resulting attribute has the set difference of its prior value set
* and the specified value set.
* If no values are specified, deletes the entire attribute.
* If the attribute does not exist, or if some or all members of the
* specified value set do not exist, this absence may be ignored
* and the operation succeeds, or a NamingException may be thrown to
* indicate the absence.
* Removal of the last value will remove the attribute if the
* attribute is required to have at least one value.
* <p>
* The value of this constant is <tt>3</tt>.
*
* @see ModificationItem
* @see #modifyAttributes
*/
public final static int REMOVE_ATTRIBUTE = 3;
/** {@collect.stats}
* Modifies the attributes associated with a named object.
* The order of the modifications is not specified. Where
* possible, the modifications are performed atomically.
*
* @param name
* the name of the object whose attributes will be updated
* @param mod_op
* the modification operation, one of:
* <code>ADD_ATTRIBUTE</code>,
* <code>REPLACE_ATTRIBUTE</code>,
* <code>REMOVE_ATTRIBUTE</code>.
* @param attrs
* the attributes to be used for the modification; may not be null
*
* @throws AttributeModificationException if the modification cannot
* be completed successfully
* @throws NamingException if a naming exception is encountered
*
* @see #modifyAttributes(Name, ModificationItem[])
*/
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Modifies the attributes associated with a named object.
* See {@link #modifyAttributes(Name, int, Attributes)} for details.
*
* @param name
* the name of the object whose attributes will be updated
* @param mod_op
* the modification operation, one of:
* <code>ADD_ATTRIBUTE</code>,
* <code>REPLACE_ATTRIBUTE</code>,
* <code>REMOVE_ATTRIBUTE</code>.
* @param attrs
* the attributes to be used for the modification; may not be null
*
* @throws AttributeModificationException if the modification cannot
* be completed successfully
* @throws NamingException if a naming exception is encountered
*/
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Modifies the attributes associated with a named object using
* an ordered list of modifications.
* The modifications are performed
* in the order specified. Each modification specifies a
* modification operation code and an attribute on which to
* operate. Where possible, the modifications are
* performed atomically.
*
* @param name
* the name of the object whose attributes will be updated
* @param mods
* an ordered sequence of modifications to be performed;
* may not be null
*
* @throws AttributeModificationException if the modifications
* cannot be completed successfully
* @throws NamingException if a naming exception is encountered
*
* @see #modifyAttributes(Name, int, Attributes)
* @see ModificationItem
*/
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException;
/** {@collect.stats}
* Modifies the attributes associated with a named object using
* an ordered list of modifications.
* See {@link #modifyAttributes(Name, ModificationItem[])} for details.
*
* @param name
* the name of the object whose attributes will be updated
* @param mods
* an ordered sequence of modifications to be performed;
* may not be null
*
* @throws AttributeModificationException if the modifications
* cannot be completed successfully
* @throws NamingException if a naming exception is encountered
*/
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException;
/** {@collect.stats}
* Binds a name to an object, along with associated attributes.
* If <tt>attrs</tt> is null, the resulting binding will have
* the attributes associated with <tt>obj</tt> if <tt>obj</tt> is a
* <tt>DirContext</tt>, and no attributes otherwise.
* If <tt>attrs</tt> is non-null, the resulting binding will have
* <tt>attrs</tt> as its attributes; any attributes associated with
* <tt>obj</tt> are ignored.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @param attrs
* the attributes to associate with the binding
*
* @throws NameAlreadyBoundException if name is already bound
* @throws InvalidAttributesException if some "mandatory" attributes
* of the binding are not supplied
* @throws NamingException if a naming exception is encountered
*
* @see Context#bind(Name, Object)
* @see #rebind(Name, Object, Attributes)
*/
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Binds a name to an object, along with associated attributes.
* See {@link #bind(Name, Object, Attributes)} for details.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @param attrs
* the attributes to associate with the binding
*
* @throws NameAlreadyBoundException if name is already bound
* @throws InvalidAttributesException if some "mandatory" attributes
* of the binding are not supplied
* @throws NamingException if a naming exception is encountered
*/
public void bind(String name, Object obj, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Binds a name to an object, along with associated attributes,
* overwriting any existing binding.
* If <tt>attrs</tt> is null and <tt>obj</tt> is a <tt>DirContext</tt>,
* the attributes from <tt>obj</tt> are used.
* If <tt>attrs</tt> is null and <tt>obj</tt> is not a <tt>DirContext</tt>,
* any existing attributes associated with the object already bound
* in the directory remain unchanged.
* If <tt>attrs</tt> is non-null, any existing attributes associated with
* the object already bound in the directory are removed and <tt>attrs</tt>
* is associated with the named object. If <tt>obj</tt> is a
* <tt>DirContext</tt> and <tt>attrs</tt> is non-null, the attributes
* of <tt>obj</tt> are ignored.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @param attrs
* the attributes to associate with the binding
*
* @throws InvalidAttributesException if some "mandatory" attributes
* of the binding are not supplied
* @throws NamingException if a naming exception is encountered
*
* @see Context#bind(Name, Object)
* @see #bind(Name, Object, Attributes)
*/
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Binds a name to an object, along with associated attributes,
* overwriting any existing binding.
* See {@link #rebind(Name, Object, Attributes)} for details.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @param attrs
* the attributes to associate with the binding
*
* @throws InvalidAttributesException if some "mandatory" attributes
* of the binding are not supplied
* @throws NamingException if a naming exception is encountered
*/
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Creates and binds a new context, along with associated attributes.
* This method creates a new subcontext with the given name, binds it in
* the target context (that named by all but terminal atomic
* component of the name), and associates the supplied attributes
* with the newly created object.
* All intermediate and target contexts must already exist.
* If <tt>attrs</tt> is null, this method is equivalent to
* <tt>Context.createSubcontext()</tt>.
*
* @param name
* the name of the context to create; may not be empty
* @param attrs
* the attributes to associate with the newly created context
* @return the newly created context
*
* @throws NameAlreadyBoundException if the name is already bound
* @throws InvalidAttributesException if <code>attrs</code> does not
* contain all the mandatory attributes required for creation
* @throws NamingException if a naming exception is encountered
*
* @see Context#createSubcontext(Name)
*/
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException;
/** {@collect.stats}
* Creates and binds a new context, along with associated attributes.
* See {@link #createSubcontext(Name, Attributes)} for details.
*
* @param name
* the name of the context to create; may not be empty
* @param attrs
* the attributes to associate with the newly created context
* @return the newly created context
*
* @throws NameAlreadyBoundException if the name is already bound
* @throws InvalidAttributesException if <code>attrs</code> does not
* contain all the mandatory attributes required for creation
* @throws NamingException if a naming exception is encountered
*/
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException;
// -------------------- schema operations
/** {@collect.stats}
* Retrieves the schema associated with the named object.
* The schema describes rules regarding the structure of the namespace
* and the attributes stored within it. The schema
* specifies what types of objects can be added to the directory and where
* they can be added; what mandatory and optional attributes an object
* can have. The range of support for schemas is directory-specific.
*
* <p> This method returns the root of the schema information tree
* that is applicable to the named object. Several named objects
* (or even an entire directory) might share the same schema.
*
* <p> Issues such as structure and contents of the schema tree,
* permission to modify to the contents of the schema
* tree, and the effect of such modifications on the directory
* are dependent on the underlying directory.
*
* @param name
* the name of the object whose schema is to be retrieved
* @return the schema associated with the context; never null
* @throws OperationNotSupportedException if schema not supported
* @throws NamingException if a naming exception is encountered
*/
public DirContext getSchema(Name name) throws NamingException;
/** {@collect.stats}
* Retrieves the schema associated with the named object.
* See {@link #getSchema(Name)} for details.
*
* @param name
* the name of the object whose schema is to be retrieved
* @return the schema associated with the context; never null
* @throws OperationNotSupportedException if schema not supported
* @throws NamingException if a naming exception is encountered
*/
public DirContext getSchema(String name) throws NamingException;
/** {@collect.stats}
* Retrieves a context containing the schema objects of the
* named object's class definitions.
*<p>
* One category of information found in directory schemas is
* <em>class definitions</em>. An "object class" definition
* specifies the object's <em>type</em> and what attributes (mandatory
* and optional) the object must/can have. Note that the term
* "object class" being referred to here is in the directory sense
* rather than in the Java sense.
* For example, if the named object is a directory object of
* "Person" class, <tt>getSchemaClassDefinition()</tt> would return a
* <tt>DirContext</tt> representing the (directory's) object class
* definition of "Person".
*<p>
* The information that can be retrieved from an object class definition
* is directory-dependent.
*<p>
* Prior to JNDI 1.2, this method
* returned a single schema object representing the class definition of
* the named object.
* Since JNDI 1.2, this method returns a <tt>DirContext</tt> containing
* all of the named object's class definitions.
*
* @param name
* the name of the object whose object class
* definition is to be retrieved
* @return the <tt>DirContext</tt> containing the named
* object's class definitions; never null
*
* @throws OperationNotSupportedException if schema not supported
* @throws NamingException if a naming exception is encountered
*/
public DirContext getSchemaClassDefinition(Name name)
throws NamingException;
/** {@collect.stats}
* Retrieves a context containing the schema objects of the
* named object's class definitions.
* See {@link #getSchemaClassDefinition(Name)} for details.
*
* @param name
* the name of the object whose object class
* definition is to be retrieved
* @return the <tt>DirContext</tt> containing the named
* object's class definitions; never null
*
* @throws OperationNotSupportedException if schema not supported
* @throws NamingException if a naming exception is encountered
*/
public DirContext getSchemaClassDefinition(String name)
throws NamingException;
// -------------------- search operations
/** {@collect.stats}
* Searches in a single context for objects that contain a
* specified set of attributes, and retrieves selected attributes.
* The search is performed using the default
* <code>SearchControls</code> settings.
* <p>
* For an object to be selected, each attribute in
* <code>matchingAttributes</code> must match some attribute of the
* object. If <code>matchingAttributes</code> is empty or
* null, all objects in the target context are returned.
*<p>
* An attribute <em>A</em><sub>1</sub> in
* <code>matchingAttributes</code> is considered to match an
* attribute <em>A</em><sub>2</sub> of an object if
* <em>A</em><sub>1</sub> and <em>A</em><sub>2</sub> have the same
* identifier, and each value of <em>A</em><sub>1</sub> is equal
* to some value of <em>A</em><sub>2</sub>. This implies that the
* order of values is not significant, and that
* <em>A</em><sub>2</sub> may contain "extra" values not found in
* <em>A</em><sub>1</sub> without affecting the comparison. It
* also implies that if <em>A</em><sub>1</sub> has no values, then
* testing for a match is equivalent to testing for the presence
* of an attribute <em>A</em><sub>2</sub> with the same
* identifier.
*<p>
* The precise definition of "equality" used in comparing attribute values
* is defined by the underlying directory service. It might use the
* <code>Object.equals</code> method, for example, or might use a schema
* to specify a different equality operation.
* For matching based on operations other than equality (such as
* substring comparison) use the version of the <code>search</code>
* method that takes a filter argument.
* <p>
* When changes are made to this <tt>DirContext</tt>,
* the effect on enumerations returned by prior calls to this method
* is undefined.
*<p>
* If the object does not have the attribute
* specified, the directory will ignore the nonexistent attribute
* and return the requested attributes that the object does have.
*<p>
* A directory might return more attributes than was requested
* (see <strong>Attribute Type Names</strong> in the class description),
* but is not allowed to return arbitrary, unrelated attributes.
*<p>
* See also <strong>Operational Attributes</strong> in the class
* description.
*
* @param name
* the name of the context to search
* @param matchingAttributes
* the attributes to search for. If empty or null,
* all objects in the target context are returned.
* @param attributesToReturn
* the attributes to return. null indicates that
* all attributes are to be returned;
* an empty array indicates that none are to be returned.
* @return
* a non-null enumeration of <tt>SearchResult</tt> objects.
* Each <tt>SearchResult</tt> contains the attributes
* identified by <code>attributesToReturn</code>
* and the name of the corresponding object, named relative
* to the context named by <code>name</code>.
* @throws NamingException if a naming exception is encountered
*
* @see SearchControls
* @see SearchResult
* @see #search(Name, String, Object[], SearchControls)
*/
public NamingEnumeration<SearchResult>
search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException;
/** {@collect.stats}
* Searches in a single context for objects that contain a
* specified set of attributes, and retrieves selected attributes.
* See {@link #search(Name, Attributes, String[])} for details.
*
* @param name
* the name of the context to search
* @param matchingAttributes
* the attributes to search for
* @param attributesToReturn
* the attributes to return
* @return a non-null enumeration of <tt>SearchResult</tt> objects
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<SearchResult>
search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException;
/** {@collect.stats}
* Searches in a single context for objects that contain a
* specified set of attributes.
* This method returns all the attributes of such objects.
* It is equivalent to supplying null as
* the <tt>atributesToReturn</tt> parameter to the method
* <code>search(Name, Attributes, String[])</code>.
* <br>
* See {@link #search(Name, Attributes, String[])} for a full description.
*
* @param name
* the name of the context to search
* @param matchingAttributes
* the attributes to search for
* @return an enumeration of <tt>SearchResult</tt> objects
* @throws NamingException if a naming exception is encountered
*
* @see #search(Name, Attributes, String[])
*/
public NamingEnumeration<SearchResult>
search(Name name, Attributes matchingAttributes)
throws NamingException;
/** {@collect.stats}
* Searches in a single context for objects that contain a
* specified set of attributes.
* See {@link #search(Name, Attributes)} for details.
*
* @param name
* the name of the context to search
* @param matchingAttributes
* the attributes to search for
* @return an enumeration of <tt>SearchResult</tt> objects
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<SearchResult>
search(String name, Attributes matchingAttributes)
throws NamingException;
/** {@collect.stats}
* Searches in the named context or object for entries that satisfy the
* given search filter. Performs the search as specified by
* the search controls.
* <p>
* The format and interpretation of <code>filter</code> follows RFC 2254
* with the
* following interpretations for <code>attr</code> and <code>value</code>
* mentioned in the RFC.
* <p>
* <code>attr</code> is the attribute's identifier.
* <p>
* <code>value</code> is the string representation the attribute's value.
* The translation of this string representation into the attribute's value
* is directory-specific.
* <p>
* For the assertion "someCount=127", for example, <code>attr</code>
* is "someCount" and <code>value</code> is "127".
* The provider determines, based on the attribute ID ("someCount")
* (and possibly its schema), that the attribute's value is an integer.
* It then parses the string "127" appropriately.
*<p>
* Any non-ASCII characters in the filter string should be
* represented by the appropriate Java (Unicode) characters, and
* not encoded as UTF-8 octets. Alternately, the
* "backslash-hexcode" notation described in RFC 2254 may be used.
*<p>
* If the directory does not support a string representation of
* some or all of its attributes, the form of <code>search</code> that
* accepts filter arguments in the form of Objects can be used instead.
* The service provider for such a directory would then translate
* the filter arguments to its service-specific representation
* for filter evaluation.
* See <code>search(Name, String, Object[], SearchControls)</code>.
* <p>
* RFC 2254 defines certain operators for the filter, including substring
* matches, equality, approximate match, greater than, less than. These
* operators are mapped to operators with corresponding semantics in the
* underlying directory. For example, for the equals operator, suppose
* the directory has a matching rule defining "equality" of the
* attributes in the filter. This rule would be used for checking
* equality of the attributes specified in the filter with the attributes
* of objects in the directory. Similarly, if the directory has a
* matching rule for ordering, this rule would be used for
* making "greater than" and "less than" comparisons.
*<p>
* Not all of the operators defined in RFC 2254 are applicable to all
* attributes. When an operator is not applicable, the exception
* <code>InvalidSearchFilterException</code> is thrown.
* <p>
* The result is returned in an enumeration of <tt>SearchResult</tt>s.
* Each <tt>SearchResult</tt> contains the name of the object
* and other information about the object (see SearchResult).
* The name is either relative to the target context of the search
* (which is named by the <code>name</code> parameter), or
* it is a URL string. If the target context is included in
* the enumeration (as is possible when
* <code>cons</code> specifies a search scope of
* <code>SearchControls.OBJECT_SCOPE</code> or
* <code>SearchControls.SUBSTREE_SCOPE</code>), its name is the empty
* string. The <tt>SearchResult</tt> may also contain attributes of the
* matching object if the <tt>cons</tt> argument specified that attributes
* be returned.
*<p>
* If the object does not have a requested attribute, that
* nonexistent attribute will be ignored. Those requested
* attributes that the object does have will be returned.
*<p>
* A directory might return more attributes than were requested
* (see <strong>Attribute Type Names</strong> in the class description)
* but is not allowed to return arbitrary, unrelated attributes.
*<p>
* See also <strong>Operational Attributes</strong> in the class
* description.
*
* @param name
* the name of the context or object to search
* @param filter
* the filter expression to use for the search; may not be null
* @param cons
* the search controls that control the search. If null,
* the default search controls are used (equivalent
* to <tt>(new SearchControls())</tt>).
* @return an enumeration of <tt>SearchResult</tt>s of
* the objects that satisfy the filter; never null
*
* @throws InvalidSearchFilterException if the search filter specified is
* not supported or understood by the underlying directory
* @throws InvalidSearchControlsException if the search controls
* contain invalid settings
* @throws NamingException if a naming exception is encountered
*
* @see #search(Name, String, Object[], SearchControls)
* @see SearchControls
* @see SearchResult
*/
public NamingEnumeration<SearchResult>
search(Name name,
String filter,
SearchControls cons)
throws NamingException;
/** {@collect.stats}
* Searches in the named context or object for entries that satisfy the
* given search filter. Performs the search as specified by
* the search controls.
* See {@link #search(Name, String, SearchControls)} for details.
*
* @param name
* the name of the context or object to search
* @param filter
* the filter expression to use for the search; may not be null
* @param cons
* the search controls that control the search. If null,
* the default search controls are used (equivalent
* to <tt>(new SearchControls())</tt>).
*
* @return an enumeration of <tt>SearchResult</tt>s for
* the objects that satisfy the filter.
* @throws InvalidSearchFilterException if the search filter specified is
* not supported or understood by the underlying directory
* @throws InvalidSearchControlsException if the search controls
* contain invalid settings
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<SearchResult>
search(String name,
String filter,
SearchControls cons)
throws NamingException;
/** {@collect.stats}
* Searches in the named context or object for entries that satisfy the
* given search filter. Performs the search as specified by
* the search controls.
*<p>
* The interpretation of <code>filterExpr</code> is based on RFC
* 2254. It may additionally contain variables of the form
* <code>{i}</code> -- where <code>i</code> is an integer -- that
* refer to objects in the <code>filterArgs</code> array. The
* interpretation of <code>filterExpr</code> is otherwise
* identical to that of the <code>filter</code> parameter of the
* method <code>search(Name, String, SearchControls)</code>.
*<p>
* When a variable <code>{i}</code> appears in a search filter, it
* indicates that the filter argument <code>filterArgs[i]</code>
* is to be used in that place. Such variables may be used
* wherever an <em>attr</em>, <em>value</em>, or
* <em>matchingrule</em> production appears in the filter grammar
* of RFC 2254, section 4. When a string-valued filter argument
* is substituted for a variable, the filter is interpreted as if
* the string were given in place of the variable, with any
* characters having special significance within filters (such as
* <code>'*'</code>) having been escaped according to the rules of
* RFC 2254.
*<p>
* For directories that do not use a string representation for
* some or all of their attributes, the filter argument
* corresponding to an attribute value may be of a type other than
* String. Directories that support unstructured binary-valued
* attributes, for example, should accept byte arrays as filter
* arguments. The interpretation (if any) of filter arguments of
* any other type is determined by the service provider for that
* directory, which maps the filter operations onto operations with
* corresponding semantics in the underlying directory.
*<p>
* This method returns an enumeration of the results.
* Each element in the enumeration contains the name of the object
* and other information about the object (see <code>SearchResult</code>).
* The name is either relative to the target context of the search
* (which is named by the <code>name</code> parameter), or
* it is a URL string. If the target context is included in
* the enumeration (as is possible when
* <code>cons</code> specifies a search scope of
* <code>SearchControls.OBJECT_SCOPE</code> or
* <code>SearchControls.SUBSTREE_SCOPE</code>),
* its name is the empty string.
*<p>
* The <tt>SearchResult</tt> may also contain attributes of the matching
* object if the <tt>cons</tt> argument specifies that attributes be
* returned.
*<p>
* If the object does not have a requested attribute, that
* nonexistent attribute will be ignored. Those requested
* attributes that the object does have will be returned.
*<p>
* A directory might return more attributes than were requested
* (see <strong>Attribute Type Names</strong> in the class description)
* but is not allowed to return arbitrary, unrelated attributes.
*<p>
* If a search filter with invalid variable substitutions is provided
* to this method, the result is undefined.
* When changes are made to this DirContext,
* the effect on enumerations returned by prior calls to this method
* is undefined.
*<p>
* See also <strong>Operational Attributes</strong> in the class
* description.
*
* @param name
* the name of the context or object to search
* @param filterExpr
* the filter expression to use for the search.
* The expression may contain variables of the
* form "<code>{i}</code>" where <code>i</code>
* is a nonnegative integer. May not be null.
* @param filterArgs
* the array of arguments to substitute for the variables
* in <code>filterExpr</code>. The value of
* <code>filterArgs[i]</code> will replace each
* occurrence of "<code>{i}</code>".
* If null, equivalent to an empty array.
* @param cons
* the search controls that control the search. If null,
* the default search controls are used (equivalent
* to <tt>(new SearchControls())</tt>).
* @return an enumeration of <tt>SearchResult</tt>s of the objects
* that satisfy the filter; never null
*
* @throws ArrayIndexOutOfBoundsException if <tt>filterExpr</tt> contains
* <code>{i}</code> expressions where <code>i</code> is outside
* the bounds of the array <code>filterArgs</code>
* @throws InvalidSearchControlsException if <tt>cons</tt> contains
* invalid settings
* @throws InvalidSearchFilterException if <tt>filterExpr</tt> with
* <tt>filterArgs</tt> represents an invalid search filter
* @throws NamingException if a naming exception is encountered
*
* @see #search(Name, Attributes, String[])
* @see java.text.MessageFormat
*/
public NamingEnumeration<SearchResult>
search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException;
/** {@collect.stats}
* Searches in the named context or object for entries that satisfy the
* given search filter. Performs the search as specified by
* the search controls.
* See {@link #search(Name, String, Object[], SearchControls)} for details.
*
* @param name
* the name of the context or object to search
* @param filterExpr
* the filter expression to use for the search.
* The expression may contain variables of the
* form "<code>{i}</code>" where <code>i</code>
* is a nonnegative integer. May not be null.
* @param filterArgs
* the array of arguments to substitute for the variables
* in <code>filterExpr</code>. The value of
* <code>filterArgs[i]</code> will replace each
* occurrence of "<code>{i}</code>".
* If null, equivalent to an empty array.
* @param cons
* the search controls that control the search. If null,
* the default search controls are used (equivalent
* to <tt>(new SearchControls())</tt>).
* @return an enumeration of <tt>SearchResult</tt>s of the objects
* that satisfy the filter; never null
*
* @throws ArrayIndexOutOfBoundsException if <tt>filterExpr</tt> contains
* <code>{i}</code> expressions where <code>i</code> is outside
* the bounds of the array <code>filterArgs</code>
* @throws InvalidSearchControlsException if <tt>cons</tt> contains
* invalid settings
* @throws InvalidSearchFilterException if <tt>filterExpr</tt> with
* <tt>filterArgs</tt> represents an invalid search filter
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<SearchResult>
search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
/** {@collect.stats}
* This interface represents a collection of attributes.
*<p>
* In a directory, named objects can have associated with them
* attributes. The Attributes interface represents a collection of attributes.
* For example, you can request from the directory the attributes
* associated with an object. Those attributes are returned in
* an object that implements the Attributes interface.
*<p>
* Attributes in an object that implements the Attributes interface are
* unordered. The object can have zero or more attributes.
* Attributes is either case-sensitive or case-insensitive (case-ignore).
* This property is determined at the time the Attributes object is
* created. (see BasicAttributes constructor for example).
* In a case-insensitive Attributes, the case of its attribute identifiers
* is ignored when searching for an attribute, or adding attributes.
* In a case-sensitive Attributes, the case is significant.
*<p>
* Note that updates to Attributes (such as adding or removing an attribute)
* do not affect the corresponding representation in the directory.
* Updates to the directory can only be effected
* using operations in the DirContext interface.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirContext#getAttributes
* @see DirContext#modifyAttributes
* @see DirContext#bind
* @see DirContext#rebind
* @see DirContext#createSubcontext
* @see DirContext#search
* @see BasicAttributes
* @since 1.3
*/
public interface Attributes extends Cloneable, java.io.Serializable {
/** {@collect.stats}
* Determines whether the attribute set ignores the case of
* attribute identifiers when retrieving or adding attributes.
* @return true if case is ignored; false otherwise.
*/
boolean isCaseIgnored();
/** {@collect.stats}
* Retrieves the number of attributes in the attribute set.
*
* @return The nonnegative number of attributes in this attribute set.
*/
int size();
/** {@collect.stats}
* Retrieves the attribute with the given attribute id from the
* attribute set.
*
* @param attrID The non-null id of the attribute to retrieve.
* If this attribute set ignores the character
* case of its attribute ids, the case of attrID
* is ignored.
* @return The attribute identified by attrID; null if not found.
* @see #put
* @see #remove
*/
Attribute get(String attrID);
/** {@collect.stats}
* Retrieves an enumeration of the attributes in the attribute set.
* The effects of updates to this attribute set on this enumeration
* are undefined.
*
* @return A non-null enumeration of the attributes in this attribute set.
* Each element of the enumeration is of class <tt>Attribute</tt>.
* If attribute set has zero attributes, an empty enumeration
* is returned.
*/
NamingEnumeration<? extends Attribute> getAll();
/** {@collect.stats}
* Retrieves an enumeration of the ids of the attributes in the
* attribute set.
* The effects of updates to this attribute set on this enumeration
* are undefined.
*
* @return A non-null enumeration of the attributes' ids in
* this attribute set. Each element of the enumeration is
* of class String.
* If attribute set has zero attributes, an empty enumeration
* is returned.
*/
NamingEnumeration<String> getIDs();
/** {@collect.stats}
* Adds a new attribute to the attribute set.
*
* @param attrID non-null The id of the attribute to add.
* If the attribute set ignores the character
* case of its attribute ids, the case of attrID
* is ignored.
* @param val The possibly null value of the attribute to add.
* If null, the attribute does not have any values.
* @return The Attribute with attrID that was previous in this attribute set;
* null if no such attribute existed.
* @see #remove
*/
Attribute put(String attrID, Object val);
/** {@collect.stats}
* Adds a new attribute to the attribute set.
*
* @param attr The non-null attribute to add.
* If the attribute set ignores the character
* case of its attribute ids, the case of
* attr's identifier is ignored.
* @return The Attribute with the same ID as attr that was previous
* in this attribute set;
* null if no such attribute existed.
* @see #remove
*/
Attribute put(Attribute attr);
/** {@collect.stats}
* Removes the attribute with the attribute id 'attrID' from
* the attribute set. If the attribute does not exist, ignore.
*
* @param attrID The non-null id of the attribute to remove.
* If the attribute set ignores the character
* case of its attribute ids, the case of
* attrID is ignored.
* @return The Attribute with the same ID as attrID that was previous
* in the attribute set;
* null if no such attribute existed.
*/
Attribute remove(String attrID);
/** {@collect.stats}
* Makes a copy of the attribute set.
* The new set contains the same attributes as the original set:
* the attributes are not themselves cloned.
* Changes to the copy will not affect the original and vice versa.
*
* @return A non-null copy of this attribute set.
*/
Object clone();
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
// static final long serialVersionUID = -7247874645443605347L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when an attempt is
* made to add to create an attribute with an invalid attribute identifier.
* The validity of an attribute identifier is directory-specific.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidAttributeIdentifierException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InvalidAttributeIdentifierException using the
* explanation supplied. All other fields set to null.
* @param explanation Possibly null string containing additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public InvalidAttributeIdentifierException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of InvalidAttributeIdentifierException.
* All fields are set to null.
*/
public InvalidAttributeIdentifierException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -9036920266322999923L;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when an attempt is
* made to add, or remove, or modify an attribute, its identifier,
* or its values that conflicts with the attribute's (schema) definition
* or the attribute's state.
* It is thrown in response to DirContext.modifyAttributes().
* It contains a list of modifications that have not been performed, in the
* order that they were supplied to modifyAttributes().
* If the list is null, none of the modifications were performed successfully.
*<p>
* An AttributeModificationException instance is not synchronized
* against concurrent multithreaded access. Multiple threads trying
* to access and modify a single AttributeModification instance
* should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirContext#modifyAttributes
* @since 1.3
*/
/*
*<p>
* The serialized form of an AttributeModificationException object
* consists of the serialized fields of its NamingException
* superclass, followed by an array of ModificationItem objects.
*
*/
public class AttributeModificationException extends NamingException {
/** {@collect.stats}
* Contains the possibly null list of unexecuted modifications.
* @serial
*/
private ModificationItem[] unexecs = null;
/** {@collect.stats}
* Constructs a new instance of AttributeModificationException using
* an explanation. All other fields are set to null.
*
* @param explanation Possibly null additional detail about this exception.
* If null, this exception has no detail message.
* @see java.lang.Throwable#getMessage
*/
public AttributeModificationException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of AttributeModificationException.
* All fields are set to null.
*/
public AttributeModificationException() {
super();
}
/** {@collect.stats}
* Sets the unexecuted modification list to be e.
* Items in the list must appear in the same order in which they were
* originally supplied in DirContext.modifyAttributes().
* The first item in the list is the first one that was not executed.
* If this list is null, none of the operations originally submitted
* to modifyAttributes() were executed.
* @param e The possibly null list of unexecuted modifications.
* @see #getUnexecutedModifications
*/
public void setUnexecutedModifications(ModificationItem[] e) {
unexecs = e;
}
/** {@collect.stats}
* Retrieves the unexecuted modification list.
* Items in the list appear in the same order in which they were
* originally supplied in DirContext.modifyAttributes().
* The first item in the list is the first one that was not executed.
* If this list is null, none of the operations originally submitted
* to modifyAttributes() were executed.
* @return The possibly null unexecuted modification list.
* @see #setUnexecutedModifications
*/
public ModificationItem[] getUnexecutedModifications() {
return unexecs;
}
/** {@collect.stats}
* The string representation of this exception consists of
* information about where the error occurred, and
* the first unexecuted modification.
* This string is meant for debugging and not mean to be interpreted
* programmatically.
* @return The non-null string representation of this exception.
*/
public String toString() {
String orig = super.toString();
if (unexecs != null) {
orig += ("First unexecuted modification: " +
unexecs[0].toString());
}
return orig;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 8060676069678710186L;
}
|
Java
|
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
/** {@collect.stats}
* This class represents a modification item.
* It consists of a modification code and an attribute on which to operate.
*<p>
* A ModificationItem instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single ModificationItem instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
/*
*<p>
* The serialized form of a ModificationItem object consists of the
* modification op (and int) and the corresponding Attribute.
*/
public class ModificationItem implements java.io.Serializable {
/** {@collect.stats}
* Contains an integer identify the modification
* to be performed.
* @serial
*/
private int mod_op;
/** {@collect.stats}
* Contains the attribute identifying
* the attribute and/or its value to be applied for the modification.
* @serial
*/
private Attribute attr;
/** {@collect.stats}
* Creates a new instance of ModificationItem.
* @param mod_op Modification to apply. It must be one of:
* DirContext.ADD_ATTRIBUTE
* DirContext.REPLACE_ATTRIBUTE
* DirContext.REMOVE_ATTRIBUTE
* @param attr The non-null attribute to use for modification.
* @exception IllegalArgumentException If attr is null, or if mod_op is
* not one of the ones specified above.
*/
public ModificationItem(int mod_op, Attribute attr) {
switch (mod_op) {
case DirContext.ADD_ATTRIBUTE:
case DirContext.REPLACE_ATTRIBUTE:
case DirContext.REMOVE_ATTRIBUTE:
if (attr == null)
throw new IllegalArgumentException("Must specify non-null attribute for modification");
this.mod_op = mod_op;
this.attr = attr;
break;
default:
throw new IllegalArgumentException("Invalid modification code " + mod_op);
}
}
/** {@collect.stats}
* Retrieves the modification code of this modification item.
* @return The modification code. It is one of:
* DirContext.ADD_ATTRIBUTE
* DirContext.REPLACE_ATTRIBUTE
* DirContext.REMOVE_ATTRIBUTE
*/
public int getModificationOp() {
return mod_op;
}
/** {@collect.stats}
* Retrieves the attribute associated with this modification item.
* @return The non-null attribute to use for the modification.
*/
public Attribute getAttribute() {
return attr;
}
/** {@collect.stats}
* Generates the string representation of this modification item,
* which consists of the modification operation and its related attribute.
* The string representation is meant for debugging and not to be
* interpreted programmatically.
*
* @return The non-null string representation of this modification item.
*/
public String toString() {
switch (mod_op) {
case DirContext.ADD_ATTRIBUTE:
return ("Add attribute: " + attr.toString());
case DirContext.REPLACE_ATTRIBUTE:
return ("Replace attribute: " + attr.toString());
case DirContext.REMOVE_ATTRIBUTE:
return ("Remove attribute: " + attr.toString());
}
return ""; // should never happen
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 7573258562534746850L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when the specification of
* the SearchControls for a search operation is invalid. For example, if the scope is
* set to a value other than OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE,
* this exception is thrown.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidSearchControlsException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InvalidSearchControlsException.
* All fields are set to null.
*/
public InvalidSearchControlsException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of InvalidSearchControlsException
* with an explanation. All other fields set to null.
* @param msg Detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public InvalidSearchControlsException(String msg) {
super(msg);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -5124108943352665777L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when an attempt is
* made to add or modify an attribute set that has been specified
* incompletely or incorrectly. This could happen, for example,
* when attempting to add or modify a binding, or to create a new
* subcontext without specifying all the mandatory attributes
* required for creation of the object. Another situation in
* which this exception is thrown is by specification of incompatible
* attributes within the same attribute set, or attributes in conflict
* with that specified by the object's schema.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class InvalidAttributesException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of InvalidAttributesException using an
* explanation. All other fields are set to null.
* @param explanation Additional detail about this exception. Can be null.
* @see java.lang.Throwable#getMessage
*/
public InvalidAttributesException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of InvalidAttributesException.
* All fields are set to null.
*/
public InvalidAttributesException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 2607612850539889765L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.directory;
import javax.naming.NamingException;
/** {@collect.stats}
* This exception is thrown when an operation attempts
* to add an attribute that already exists.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see DirContext#modifyAttributes
* @since 1.3
*/
public class AttributeInUseException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of AttributeInUseException with
* an explanation. All other fields are set to null.
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public AttributeInUseException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of AttributeInUseException.
* All fields are initialized to null.
*/
public AttributeInUseException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 4437710305529322564L;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
import java.util.Hashtable;
/** {@collect.stats}
* This exception is thrown to indicate that the operation reached
* a point in the name where the operation cannot proceed any further.
* When performing an operation on a composite name, a naming service
* provider may reach a part of the name that does not belong to its
* namespace. At that point, it can construct a
* CannotProceedException and then invoke methods provided by
* javax.naming.spi.NamingManager (such as getContinuationContext())
* to locate another provider to continue the operation. If this is
* not possible, this exception is raised to the caller of the
* context operation.
*<p>
* If the program wants to handle this exception in particular, it
* should catch CannotProceedException explicitly before attempting to
* catch NamingException.
*<p>
* A CannotProceedException instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* CannotProceedException should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
/*
* The serialized form of a CannotProceedException object consists of
* the serialized fields of its NamingException superclass, the remaining new
* name (a Name object), the environment (a Hashtable), the altName field
* (a Name object), and the serialized form of the altNameCtx field.
*/
public class CannotProceedException extends NamingException {
/** {@collect.stats}
* Contains the remaining unresolved part of the second
* "name" argument to Context.rename().
* This information necessary for
* continuing the Context.rename() operation.
* <p>
* This field is initialized to null.
* It should not be manipulated directly: it should
* be accessed and updated using getRemainingName() and setRemainingName().
* @serial
*
* @see #getRemainingNewName
* @see #setRemainingNewName
*/
protected Name remainingNewName = null;
/** {@collect.stats}
* Contains the environment
* relevant for the Context or DirContext method that cannot proceed.
* <p>
* This field is initialized to null.
* It should not be manipulated directly: it should be accessed
* and updated using getEnvironment() and setEnvironment().
* @serial
*
* @see #getEnvironment
* @see #setEnvironment
*/
protected Hashtable<?,?> environment = null;
/** {@collect.stats}
* Contains the name of the resolved object, relative
* to the context <code>altNameCtx</code>. It is a composite name.
* If null, then no name is specified.
* See the <code>javax.naming.spi.ObjectFactory.getObjectInstance</code>
* method for details on how this is used.
* <p>
* This field is initialized to null.
* It should not be manipulated directly: it should
* be accessed and updated using getAltName() and setAltName().
* @serial
*
* @see #getAltName
* @see #setAltName
* @see #altNameCtx
* @see javax.naming.spi.ObjectFactory#getObjectInstance
*/
protected Name altName = null;
/** {@collect.stats}
* Contains the context relative to which
* <code>altName</code> is specified. If null, then the default initial
* context is implied.
* See the <code>javax.naming.spi.ObjectFactory.getObjectInstance</code>
* method for details on how this is used.
* <p>
* This field is initialized to null.
* It should not be manipulated directly: it should
* be accessed and updated using getAltNameCtx() and setAltNameCtx().
* @serial
*
* @see #getAltNameCtx
* @see #setAltNameCtx
* @see #altName
* @see javax.naming.spi.ObjectFactory#getObjectInstance
*/
protected Context altNameCtx = null;
/** {@collect.stats}
* Constructs a new instance of CannotProceedException using an
* explanation. All unspecified fields default to null.
*
* @param explanation A possibly null string containing additional
* detail about this exception.
* If null, this exception has no detail message.
* @see java.lang.Throwable#getMessage
*/
public CannotProceedException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of CannotProceedException.
* All fields default to null.
*/
public CannotProceedException() {
super();
}
/** {@collect.stats}
* Retrieves the environment that was in effect when this exception
* was created.
* @return Possibly null environment property set.
* null means no environment was recorded for this exception.
* @see #setEnvironment
*/
public Hashtable<?,?> getEnvironment() {
return environment;
}
/** {@collect.stats}
* Sets the environment that will be returned when getEnvironment()
* is called.
* @param environment A possibly null environment property set.
* null means no environment is being recorded for
* this exception.
* @see #getEnvironment
*/
public void setEnvironment(Hashtable<?,?> environment) {
this.environment = environment; // %%% clone it??
}
/** {@collect.stats}
* Retrieves the "remaining new name" field of this exception, which is
* used when this exception is thrown during a rename() operation.
*
* @return The possibly null part of the new name that has not been resolved.
* It is a composite name. It can be null, which means
* the remaining new name field has not been set.
*
* @see #setRemainingNewName
*/
public Name getRemainingNewName() {
return remainingNewName;
}
/** {@collect.stats}
* Sets the "remaining new name" field of this exception.
* This is the value returned by <code>getRemainingNewName()</code>.
*<p>
* <tt>newName</tt> is a composite name. If the intent is to set
* this field using a compound name or string, you must
* "stringify" the compound name, and create a composite
* name with a single component using the string. You can then
* invoke this method using the resulting composite name.
*<p>
* A copy of <code>newName</code> is made and stored.
* Subsequent changes to <code>name</code> does not
* affect the copy in this NamingException and vice versa.
*
* @param newName The possibly null name to set the "remaining new name" to.
* If null, it sets the remaining name field to null.
*
* @see #getRemainingNewName
*/
public void setRemainingNewName(Name newName) {
if (newName != null)
this.remainingNewName = (Name)(newName.clone());
else
this.remainingNewName = null;
}
/** {@collect.stats}
* Retrieves the <code>altName</code> field of this exception.
* This is the name of the resolved object, relative to the context
* <code>altNameCtx</code>. It will be used during a subsequent call to the
* <code>javax.naming.spi.ObjectFactory.getObjectInstance</code> method.
*
* @return The name of the resolved object, relative to
* <code>altNameCtx</code>.
* It is a composite name. If null, then no name is specified.
*
* @see #setAltName
* @see #getAltNameCtx
* @see javax.naming.spi.ObjectFactory#getObjectInstance
*/
public Name getAltName() {
return altName;
}
/** {@collect.stats}
* Sets the <code>altName</code> field of this exception.
*
* @param altName The name of the resolved object, relative to
* <code>altNameCtx</code>.
* It is a composite name.
* If null, then no name is specified.
*
* @see #getAltName
* @see #setAltNameCtx
*/
public void setAltName(Name altName) {
this.altName = altName;
}
/** {@collect.stats}
* Retrieves the <code>altNameCtx</code> field of this exception.
* This is the context relative to which <code>altName</code> is named.
* It will be used during a subsequent call to the
* <code>javax.naming.spi.ObjectFactory.getObjectInstance</code> method.
*
* @return The context relative to which <code>altName</code> is named.
* If null, then the default initial context is implied.
*
* @see #setAltNameCtx
* @see #getAltName
* @see javax.naming.spi.ObjectFactory#getObjectInstance
*/
public Context getAltNameCtx() {
return altNameCtx;
}
/** {@collect.stats}
* Sets the <code>altNameCtx</code> field of this exception.
*
* @param altNameCtx
* The context relative to which <code>altName</code>
* is named. If null, then the default initial context
* is implied.
*
* @see #getAltNameCtx
* @see #setAltName
*/
public void setAltNameCtx(Context altNameCtx) {
this.altNameCtx = altNameCtx;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 1219724816191576813L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when attempting to perform an operation
* for which the client has no permission. The access control/permission
* model is dictated by the directory/naming server.
*
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public class NoPermissionException extends NamingSecurityException {
/** {@collect.stats}
* Constructs a new instance of NoPermissionException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null additional detail about this exception.
*/
public NoPermissionException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NoPermissionException.
* All fields are initialized to null.
*/
public NoPermissionException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 8395332708699751775L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown by methods to indicate that
* a binding cannot be added because the name is already bound to
* another object.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context#bind
* @see Context#rebind
* @see Context#createSubcontext
* @see javax.naming.directory.DirContext#bind
* @see javax.naming.directory.DirContext#rebind
* @see javax.naming.directory.DirContext#createSubcontext
* @since 1.3
*/
public class NameAlreadyBoundException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of NameAlreadyBoundException using the
* explanation supplied. All other fields default to null.
*
*
* @param explanation Possibly null additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public NameAlreadyBoundException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of NameAlreadyBoundException.
* All fields are set to null;
*/
public NameAlreadyBoundException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -8491441000356780586L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when attempting to destroy a context that
* is not empty.
*<p>
* If the program wants to handle this exception in particular, it
* should catch ContextNotEmptyException explicitly before attempting to
* catch NamingException. For example, after catching ContextNotEmptyException,
* the program might try to remove the contents of the context before
* reattempting the destroy.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context#destroySubcontext
* @since 1.3
*/
public class ContextNotEmptyException extends NamingException {
/** {@collect.stats}
* Constructs a new instance of ContextNotEmptyException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null string containing
* additional detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public ContextNotEmptyException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs a new instance of ContextNotEmptyException with
* all name resolution fields and explanation initialized to null.
*/
public ContextNotEmptyException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 1090963683348219877L;
}
|
Java
|
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is thrown when the naming operation
* being invoked has been interrupted. For example, an application
* might interrupt a thread that is performing a search. If the
* search supports being interrupted, it will throw
* InterruptedNamingException. Whether an operation is interruptible
* and when depends on its implementation (as provided by the
* service providers). Different implementations have different ways
* of protecting their resources and objects from being damaged
* due to unexpected interrupts.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context
* @see javax.naming.directory.DirContext
* @see java.lang.Thread#interrupt
* @see java.lang.InterruptedException
* @since 1.3
*/
public class InterruptedNamingException extends NamingException {
/** {@collect.stats}
* Constructs an instance of InterruptedNamingException using an
* explanation of the problem.
* All name resolution-related fields are initialized to null.
* @param explanation A possibly null message explaining the problem.
* @see java.lang.Throwable#getMessage
*/
public InterruptedNamingException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Constructs an instance of InterruptedNamingException with
* all name resolution fields and explanation initialized to null.
*/
public InterruptedNamingException() {
super();
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 6404516648893194728L;
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
/** {@collect.stats}
* Contains methods for registering listeners to be notified
* of events fired when objects named in a directory context changes.
*<p>
* The methods in this interface support identification of objects by
* <A HREF="ftp://ftp.isi.edu/in-notes/rfc2254.txt">RFC 2254</a>
* search filters.
*
*<P>Using the search filter, it is possible to register interest in objects
* that do not exist at the time of registration but later come into existence and
* satisfy the filter. However, there might be limitations in the extent
* to which this can be supported by the service provider and underlying
* protocol/service. If the caller submits a filter that cannot be
* supported in this way, <tt>addNamingListener()</tt> throws an
* <tt>InvalidSearchFilterException</tt>.
*<p>
* See <tt>EventContext</tt> for a description of event source
* and target, and information about listener registration/deregistration
* that are also applicable to methods in this interface.
* See the
* <a href=package-summary.html#THREADING>package description</a>
* for information on threading issues.
*<p>
* A <tt>SearchControls</tt> or array object
* passed as a parameter to any method is owned by the caller.
* The service provider will not modify the object or keep a reference to it.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public interface EventDirContext extends EventContext, DirContext {
/** {@collect.stats}
* Adds a listener for receiving naming events fired
* when objects identified by the search filter <tt>filter</tt> at
* the object named by target are modified.
* <p>
* The scope, returningObj flag, and returningAttributes flag from
* the search controls <tt>ctls</tt> are used to control the selection
* of objects that the listener is interested in,
* and determines what information is returned in the eventual
* <tt>NamingEvent</tt> object. Note that the requested
* information to be returned might not be present in the <tt>NamingEvent</tt>
* object if they are unavailable or could not be obtained by the
* service provider or service.
*
* @param target The nonnull name of the object resolved relative to this context.
* @param filter The nonnull string filter (see RFC2254).
* @param ctls The possibly null search controls. If null, the default
* search controls are used.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see EventContext#removeNamingListener
* @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, javax.naming.directory.SearchControls)
*/
void addNamingListener(Name target, String filter, SearchControls ctls,
NamingListener l) throws NamingException;
/** {@collect.stats}
* Adds a listener for receiving naming events fired when
* objects identified by the search filter <tt>filter</tt> at the
* object named by the string target name are modified.
* See the overload that accepts a <tt>Name</tt> for details of
* how this method behaves.
*
* @param target The nonnull string name of the object resolved relative to this context.
* @param filter The nonnull string filter (see RFC2254).
* @param ctls The possibly null search controls. If null, the default
* search controls is used.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see EventContext#removeNamingListener
* @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, javax.naming.directory.SearchControls)
*/
void addNamingListener(String target, String filter, SearchControls ctls,
NamingListener l) throws NamingException;
/** {@collect.stats}
* Adds a listener for receiving naming events fired
* when objects identified by the search filter <tt>filter</tt> and
* filter arguments at the object named by the target are modified.
* The scope, returningObj flag, and returningAttributes flag from
* the search controls <tt>ctls</tt> are used to control the selection
* of objects that the listener is interested in,
* and determines what information is returned in the eventual
* <tt>NamingEvent</tt> object. Note that the requested
* information to be returned might not be present in the <tt>NamingEvent</tt>
* object if they are unavailable or could not be obtained by the
* service provider or service.
*
* @param target The nonnull name of the object resolved relative to this context.
* @param filter The nonnull string filter (see RFC2254).
* @param filterArgs The possibly null array of arguments for the filter.
* @param ctls The possibly null search controls. If null, the default
* search controls are used.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see EventContext#removeNamingListener
* @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, java.lang.Object[], javax.naming.directory.SearchControls)
*/
void addNamingListener(Name target, String filter, Object[] filterArgs,
SearchControls ctls, NamingListener l) throws NamingException;
/** {@collect.stats}
* Adds a listener for receiving naming events fired when
* objects identified by the search filter <tt>filter</tt>
* and filter arguments at the
* object named by the string target name are modified.
* See the overload that accepts a <tt>Name</tt> for details of
* how this method behaves.
*
* @param target The nonnull string name of the object resolved relative to this context.
* @param filter The nonnull string filter (see RFC2254).
* @param filterArgs The possibly null array of arguments for the filter.
* @param ctls The possibly null search controls. If null, the default
* search controls is used.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see EventContext#removeNamingListener
* @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, java.lang.Object[], javax.naming.directory.SearchControls) */
void addNamingListener(String target, String filter, Object[] filterArgs,
SearchControls ctls, NamingListener l) throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
import javax.naming.Binding;
/** {@collect.stats}
* This class represents an event fired by a naming/directory service.
*<p>
* The <tt>NamingEvent</tt>'s state consists of
* <ul>
* <li>The event source: the <tt>EventContext</tt> which fired this event.
* <li>The event type.
* <li>The new binding: information about the object after the change.
* <li>The old binding: information about the object before the change.
* <li>Change information: information about the change
* that triggered this event; usually service provider-specific or server-specific
* information.
* </ul>
* <p>
* Note that the event source is always the same <tt>EventContext</tt>
* <em>instance</em> that the listener has registered with.
* Furthermore, the names of the bindings in
* the <tt>NamingEvent</tt> are always relative to that instance.
* For example, suppose a listener makes the following registration:
*<blockquote><pre>
* NamespaceChangeListener listener = ...;
* src.addNamingListener("x", SUBTREE_SCOPE, listener);
*</pre></blockquote>
* When an object named "x/y" is subsequently deleted, the corresponding
* <tt>NamingEvent</tt> (<tt>evt</tt>) must contain:
*<blockquote><pre>
* evt.getEventContext() == src
* evt.getOldBinding().getName().equals("x/y")
*</pre></blockquote>
*
* Care must be taken when multiple threads are accessing the same
* <tt>EventContext</tt> concurrently.
* See the
* <a href=package-summary.html#THREADING>package description</a>
* for more information on threading issues.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingListener
* @see EventContext
* @since 1.3
*/
public class NamingEvent extends java.util.EventObject {
/** {@collect.stats}
* Naming event type for indicating that a new object has been added.
* The value of this constant is <tt>0</tt>.
*/
public static final int OBJECT_ADDED = 0;
/** {@collect.stats}
* Naming event type for indicating that an object has been removed.
* The value of this constant is <tt>1</tt>.
*/
public static final int OBJECT_REMOVED = 1;
/** {@collect.stats}
* Naming event type for indicating that an object has been renamed.
* Note that some services might fire multiple events for a single
* logical rename operation. For example, the rename operation might
* be implemented by adding a binding with the new name and removing
* the old binding.
*<p>
* The old/new binding in <tt>NamingEvent</tt> may be null if the old
* name or new name is outside of the scope for which the listener
* has registered.
*<p>
* When an interior node in the namespace tree has been renamed, the
* topmost node which is part of the listener's scope should used to generate
* a rename event. The extent to which this can be supported is
* provider-specific. For example, a service might generate rename
* notifications for all descendants of the changed interior node and the
* corresponding provider might not be able to prevent those
* notifications from being propagated to the listeners.
*<p>
* The value of this constant is <tt>2</tt>.
*/
public static final int OBJECT_RENAMED = 2;
/** {@collect.stats}
* Naming event type for indicating that an object has been changed.
* The changes might include the object's attributes, or the object itself.
* Note that some services might fire multiple events for a single
* modification. For example, the modification might
* be implemented by first removing the old binding and adding
* a new binding containing the same name but a different object.
*<p>
* The value of this constant is <tt>3</tt>.
*/
public static final int OBJECT_CHANGED = 3;
/** {@collect.stats}
* Contains information about the change that generated this event.
* @serial
*/
protected Object changeInfo;
/** {@collect.stats}
* Contains the type of this event.
* @see #OBJECT_ADDED
* @see #OBJECT_REMOVED
* @see #OBJECT_RENAMED
* @see #OBJECT_CHANGED
* @serial
*/
protected int type;
/** {@collect.stats}
* Contains information about the object before the change.
* @serial
*/
protected Binding oldBinding;
/** {@collect.stats}
* Contains information about the object after the change.
* @serial
*/
protected Binding newBinding;
/** {@collect.stats}
* Constructs an instance of <tt>NamingEvent</tt>.
*<p>
* The names in <tt>newBd</tt> and <tt>oldBd</tt> are to be resolved relative
* to the event source <tt>source</tt>.
*
* For an <tt>OBJECT_ADDED</tt> event type, <tt>newBd</tt> must not be null.
* For an <tt>OBJECT_REMOVED</tt> event type, <tt>oldBd</tt> must not be null.
* For an <tt>OBJECT_CHANGED</tt> event type, <tt>newBd</tt> and
* <tt>oldBd</tt> must not be null. For an <tt>OBJECT_RENAMED</tt> event type,
* one of <tt>newBd</tt> or <tt>oldBd</tt> may be null if the new or old
* binding is outside of the scope for which the listener has registered.
*
* @param source The non-null context that fired this event.
* @param type The type of the event.
* @param newBd A possibly null binding before the change. See method description.
* @param oldBd A possibly null binding after the change. See method description.
* @param changeInfo A possibly null object containing information about the change.
* @see #OBJECT_ADDED
* @see #OBJECT_REMOVED
* @see #OBJECT_RENAMED
* @see #OBJECT_CHANGED
*/
public NamingEvent(EventContext source, int type,
Binding newBd, Binding oldBd, Object changeInfo) {
super(source);
this.type = type;
oldBinding = oldBd;
newBinding = newBd;
this.changeInfo = changeInfo;
}
/** {@collect.stats}
* Returns the type of this event.
* @return The type of this event.
* @see #OBJECT_ADDED
* @see #OBJECT_REMOVED
* @see #OBJECT_RENAMED
* @see #OBJECT_CHANGED
*/
public int getType() {
return type;
}
/** {@collect.stats}
* Retrieves the event source that fired this event.
* This returns the same object as <tt>EventObject.getSource()</tt>.
*<p>
* If the result of this method is used to access the
* event source, for example, to look up the object or get its attributes,
* then it needs to be locked because implementations of <tt>Context</tt>
* are not guaranteed to be thread-safe
* (and <tt>EventContext</tt> is a subinterface of <tt>Context</tt>).
* See the
* <a href=package-summary.html#THREADING>package description</a>
* for more information on threading issues.
*
* @return The non-null context that fired this event.
*/
public EventContext getEventContext() {
return (EventContext)getSource();
}
/** {@collect.stats}
* Retrieves the binding of the object before the change.
*<p>
* The binding must be nonnull if the object existed before the change
* relative to the source context (<tt>getEventContext()</tt>).
* That is, it must be nonnull for <tt>OBJECT_REMOVED</tt> and
* <tt>OBJECT_CHANGED</tt>.
* For <tt>OBJECT_RENAMED</tt>, it is null if the object before the rename
* is outside of the scope for which the listener has registered interest;
* it is nonnull if the object is inside the scope before the rename.
*<p>
* The name in the binding is to be resolved relative
* to the event source <tt>getEventContext()</tt>.
* The object returned by <tt>Binding.getObject()</tt> may be null if
* such information is unavailable.
*
* @return The possibly null binding of the object before the change.
*/
public Binding getOldBinding() {
return oldBinding;
}
/** {@collect.stats}
* Retrieves the binding of the object after the change.
*<p>
* The binding must be nonnull if the object existed after the change
* relative to the source context (<tt>getEventContext()</tt>).
* That is, it must be nonnull for <tt>OBJECT_ADDED</tt> and
* <tt>OBJECT_CHANGED</tt>. For <tt>OBJECT_RENAMED</tt>,
* it is null if the object after the rename is outside the scope for
* which the listener registered interest; it is nonnull if the object
* is inside the scope after the rename.
*<p>
* The name in the binding is to be resolved relative
* to the event source <tt>getEventContext()</tt>.
* The object returned by <tt>Binding.getObject()</tt> may be null if
* such information is unavailable.
*
* @return The possibly null binding of the object after the change.
*/
public Binding getNewBinding() {
return newBinding;
}
/** {@collect.stats}
* Retrieves the change information for this event.
* The value of the change information is service-specific. For example,
* it could be an ID that identifies the change in a change log on the server.
*
* @return The possibly null change information of this event.
*/
public Object getChangeInfo() {
return changeInfo;
}
/** {@collect.stats}
* Invokes the appropriate listener method on this event.
* The default implementation of
* this method handles the following event types:
* <tt>OBJECT_ADDED</TT>, <TT>OBJECT_REMOVED</TT>,
* <TT>OBJECT_RENAMED</TT>, <TT>OBJECT_CHANGED</TT>.
*<p>
* The listener method is executed in the same thread
* as this method. See the
* <a href=package-summary.html#THREADING>package description</a>
* for more information on threading issues.
* @param listener The nonnull listener.
*/
public void dispatch(NamingListener listener) {
switch (type) {
case OBJECT_ADDED:
((NamespaceChangeListener)listener).objectAdded(this);
break;
case OBJECT_REMOVED:
((NamespaceChangeListener)listener).objectRemoved(this);
break;
case OBJECT_RENAMED:
((NamespaceChangeListener)listener).objectRenamed(this);
break;
case OBJECT_CHANGED:
((ObjectChangeListener)listener).objectChanged(this);
break;
}
}
private static final long serialVersionUID = -7126752885365133499L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
import javax.naming.NamingException;
/** {@collect.stats}
* This class represents an event fired when the procedures/processes
* used to collect information for notifying listeners of
* <tt>NamingEvent</tt>s threw a <tt>NamingException</tt>.
* This can happen, for example, if the server which the listener is using
* aborts subsequent to the <tt>addNamingListener()</tt> call.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingListener#namingExceptionThrown
* @see EventContext
* @since 1.3
*/
public class NamingExceptionEvent extends java.util.EventObject {
/** {@collect.stats}
* Contains the exception that was thrown
* @serial
*/
private NamingException exception;
/** {@collect.stats}
* Constructs an instance of <tt>NamingExceptionEvent</tt> using
* the context in which the <tt>NamingException</tt> was thrown and the exception
* that was thrown.
*
* @param source The non-null context in which the exception was thrown.
* @param exc The non-null <tt>NamingException</tt> that was thrown.
*
*/
public NamingExceptionEvent(EventContext source, NamingException exc) {
super(source);
exception = exc;
}
/** {@collect.stats}
* Retrieves the exception that was thrown.
* @return The exception that was thrown.
*/
public NamingException getException() {
return exception;
}
/** {@collect.stats}
* Retrieves the <tt>EventContext</tt> that fired this event.
* This returns the same object as <tt>EventObject.getSource()</tt>.
* @return The non-null <tt>EventContext</tt> that fired this event.
*/
public EventContext getEventContext() {
return (EventContext)getSource();
}
/** {@collect.stats}
* Invokes the <tt>namingExceptionThrown()</tt> method on
* a listener using this event.
* @param listener The non-null naming listener on which to invoke
* the method.
*/
public void dispatch(NamingListener listener) {
listener.namingExceptionThrown(this);
}
private static final long serialVersionUID = -4877678086134736336L;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
/** {@collect.stats}
* Specifies the methods that a listener interested in namespace changes
* must implement.
* Specifically, the listener is interested in <tt>NamingEvent</tt>s
* with event types of <tt>OBJECT_ADDED</TT>, <TT>OBJECT_RENAMED</TT>, or
* <TT>OBJECT_REMOVED</TT>.
*<p>
* Such a listener must:
*<ol>
*<li>Implement this interface and its methods.
*<li>Implement <tt>NamingListener.namingExceptionThrown()</tt> so that
* it will be notified of exceptions thrown while attempting to
* collect information about the events.
*<li>Register with the source using the source's <tt>addNamingListener()</tt>
* method.
*</ol>
* A listener that wants to be notified of <tt>OBJECT_CHANGED</tt> event types
* should also implement the <tt>ObjectChangeListener</tt>
* interface.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingEvent
* @see ObjectChangeListener
* @see EventContext
* @see EventDirContext
* @since 1.3
*/
public interface NamespaceChangeListener extends NamingListener {
/** {@collect.stats}
* Called when an object has been added.
*<p>
* The binding of the newly added object can be obtained using
* <tt>evt.getNewBinding()</tt>.
* @param evt The nonnull event.
* @see NamingEvent#OBJECT_ADDED
*/
void objectAdded(NamingEvent evt);
/** {@collect.stats}
* Called when an object has been removed.
*<p>
* The binding of the newly removed object can be obtained using
* <tt>evt.getOldBinding()</tt>.
* @param evt The nonnull event.
* @see NamingEvent#OBJECT_REMOVED
*/
void objectRemoved(NamingEvent evt);
/** {@collect.stats}
* Called when an object has been renamed.
*<p>
* The binding of the renamed object can be obtained using
* <tt>evt.getNewBinding()</tt>. Its old binding (before the rename)
* can be obtained using <tt>evt.getOldBinding()</tt>.
* One of these may be null if the old/new binding was outside the
* scope in which the listener has registered interest.
* @param evt The nonnull event.
* @see NamingEvent#OBJECT_RENAMED
*/
void objectRenamed(NamingEvent evt);
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
import javax.naming.Name;
import javax.naming.Context;
import javax.naming.NamingException;
/** {@collect.stats}
* Contains methods for registering/deregistering listeners to be notified of
* events fired when objects named in a context changes.
*<p>
*<h4>Target</h4>
* The name parameter in the <tt>addNamingListener()</tt> methods is referred
* to as the <em>target</em>. The target, along with the scope, identify
* the object(s) that the listener is interested in.
* It is possible to register interest in a target that does not exist, but
* there might be limitations in the extent to which this can be
* supported by the service provider and underlying protocol/service.
*<p>
* If a service only supports registration for existing
* targets, an attempt to register for a nonexistent target
* results in a <tt>NameNotFoundException</tt> being thrown as early as possible,
* preferably at the time <tt>addNamingListener()</tt> is called, or if that is
* not possible, the listener will receive the exception through the
* <tt>NamingExceptionEvent</tt>.
*<p>
* Also, for service providers that only support registration for existing
* targets, when the target that a listener has registered for is
* subsequently removed from the namespace, the listener is notified
* via a <tt>NamingExceptionEvent</tt> (containing a
*<tt>NameNotFoundException</tt>).
*<p>
* An application can use the method <tt>targetMustExist()</tt> to check
* whether a <tt>EventContext</tt> supports registration
* of nonexistent targets.
*<p>
*<h4>Event Source</h4>
* The <tt>EventContext</tt> instance on which you invoke the
* registration methods is the <em>event source</em> of the events that are
* (potentially) generated.
* The source is <em>not necessarily</em> the object named by the target.
* Only when the target is the empty name is the object named by the target
* the source.
* In other words, the target,
* along with the scope parameter, are used to identify
* the object(s) that the listener is interested in, but the event source
* is the <tt>EventContext</tt> instance with which the listener
* has registered.
*<p>
* For example, suppose a listener makes the following registration:
*<blockquote><pre>
* NamespaceChangeListener listener = ...;
* src.addNamingListener("x", SUBTREE_SCOPE, listener);
*</pre></blockquote>
* When an object named "x/y" is subsequently deleted, the corresponding
* <tt>NamingEvent</tt> (<tt>evt</tt>) must contain:
*<blockquote><pre>
* evt.getEventContext() == src
* evt.getOldBinding().getName().equals("x/y")
*</pre></blockquote>
*<p>
* Furthermore, listener registration/deregistration is with
* the <tt>EventContext</tt>
* <em>instance</em>, and not with the corresponding object in the namespace.
* If the program intends at some point to remove a listener, then it needs to
* keep a reference to the <tt>EventContext</tt> instance on
* which it invoked <tt>addNamingListener()</tt> (just as
* it needs to keep a reference to the listener in order to remove it
* later). It cannot expect to do a <tt>lookup()</tt> and get another instance of
* a <tt>EventContext</tt> on which to perform the deregistration.
*<h4>Lifetime of Registration</h4>
* A registered listener becomes deregistered when:
*<ul>
*<li>It is removed using <tt>removeNamingListener()</tt>.
*<li>An exception is thrown while collecting information about the events.
* That is, when the listener receives a <tt>NamingExceptionEvent</tt>.
*<li><tt>Context.close()</tt> is invoked on the <tt>EventContext</tt>
* instance with which it has registered.
</ul>
* Until that point, a <tt>EventContext</tt> instance that has outstanding
* listeners will continue to exist and be maintained by the service provider.
*
*<h4>Listener Implementations</h4>
* The registration/deregistration methods accept an instance of
* <tt>NamingListener</tt>. There are subinterfaces of <tt>NamingListener</tt>
* for different of event types of <tt>NamingEvent</tt>.
* For example, the <tt>ObjectChangeListener</tt>
* interface is for the <tt>NamingEvent.OBJECT_CHANGED</tt> event type.
* To register interest in multiple event types, the listener implementation
* should implement multiple <tt>NamingListener</tt> subinterfaces and use a
* single invocation of <tt>addNamingListener()</tt>.
* In addition to reducing the number of method calls and possibly the code size
* of the listeners, this allows some service providers to optimize the
* registration.
*
*<h4>Threading Issues</h4>
*
* Like <tt>Context</tt> instances in general, instances of
* <tt>EventContext</tt> are not guaranteed to be thread-safe.
* Care must be taken when multiple threads are accessing the same
* <tt>EventContext</tt> concurrently.
* See the
* <a href=package-summary.html#THREADING>package description</a>
* for more information on threading issues.
*
* @author Rosanna Lee
* @author Scott Seligman
* @since 1.3
*/
public interface EventContext extends Context {
/** {@collect.stats}
* Constant for expressing interest in events concerning the object named
* by the target.
*<p>
* The value of this constant is <tt>0</tt>.
*/
public final static int OBJECT_SCOPE = 0;
/** {@collect.stats}
* Constant for expressing interest in events concerning objects
* in the context named by the target,
* excluding the context named by the target.
*<p>
* The value of this constant is <tt>1</tt>.
*/
public final static int ONELEVEL_SCOPE = 1;
/** {@collect.stats}
* Constant for expressing interest in events concerning objects
* in the subtree of the object named by the target, including the object
* named by the target.
*<p>
* The value of this constant is <tt>2</tt>.
*/
public final static int SUBTREE_SCOPE = 2;
/** {@collect.stats}
* Adds a listener for receiving naming events fired
* when the object(s) identified by a target and scope changes.
*
* The event source of those events is this context. See the
* class description for a discussion on event source and target.
* See the descriptions of the constants <tt>OBJECT_SCOPE</tt>,
* <tt>ONELEVEL_SCOPE</tt>, and <tt>SUBTREE_SCOPE</tt> to see how
* <tt>scope</tt> affects the registration.
*<p>
* <tt>target</tt> needs to name a context only when <tt>scope</tt> is
* <tt>ONELEVEL_SCOPE</tt>.
* <tt>target</tt> may name a non-context if <tt>scope</tt> is either
* <tt>OBJECT_SCOPE</tt> or <tt>SUBTREE_SCOPE</tt>. Using
* <tt>SUBTREE_SCOPE</tt> for a non-context might be useful,
* for example, if the caller does not know in advance whether <tt>target</tt>
* is a context and just wants to register interest in the (possibly
* degenerate subtree) rooted at <tt>target</tt>.
*<p>
* When the listener is notified of an event, the listener may
* in invoked in a thread other than the one in which
* <tt>addNamingListener()</tt> is executed.
* Care must be taken when multiple threads are accessing the same
* <tt>EventContext</tt> concurrently.
* See the
* <a href=package-summary.html#THREADING>package description</a>
* for more information on threading issues.
*
* @param target A nonnull name to be resolved relative to this context.
* @param scope One of <tt>OBJECT_SCOPE</tt>, <tt>ONELEVEL_SCOPE</tt>, or
* <tt>SUBTREE_SCOPE</tt>.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see #removeNamingListener
*/
void addNamingListener(Name target, int scope, NamingListener l)
throws NamingException;
/** {@collect.stats}
* Adds a listener for receiving naming events fired
* when the object named by the string target name and scope changes.
*
* See the overload that accepts a <tt>Name</tt> for details.
*
* @param target The nonnull string name of the object resolved relative
* to this context.
* @param scope One of <tt>OBJECT_SCOPE</tt>, <tt>ONELEVEL_SCOPE</tt>, or
* <tt>SUBTREE_SCOPE</tt>.
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* adding the listener.
* @see #removeNamingListener
*/
void addNamingListener(String target, int scope, NamingListener l)
throws NamingException;
/** {@collect.stats}
* Removes a listener from receiving naming events fired
* by this <tt>EventContext</tt>.
* The listener may have registered more than once with this
* <tt>EventContext</tt>, perhaps with different target/scope arguments.
* After this method is invoked, the listener will no longer
* receive events with this <tt>EventContext</tt> instance
* as the event source (except for those events already in the process of
* being dispatched).
* If the listener was not, or is no longer, registered with
* this <tt>EventContext</tt> instance, this method does not do anything.
*
* @param l The nonnull listener.
* @exception NamingException If a problem was encountered while
* removing the listener.
* @see #addNamingListener
*/
void removeNamingListener(NamingListener l) throws NamingException;
/** {@collect.stats}
* Determines whether a listener can register interest in a target
* that does not exist.
*
* @return true if the target must exist; false if the target need not exist.
* @exception NamingException If the context's behavior in this regard cannot
* be determined.
*/
boolean targetMustExist() throws NamingException;
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
/** {@collect.stats}
* Specifies the method that a listener of a <tt>NamingEvent</tt>
* with event type of <tt>OBJECT_CHANGED</tt> must implement.
*<p>
* An <tt>OBJECT_CHANGED</tt> event type is fired when (the contents of)
* an object has changed. This might mean that its attributes have been modified,
* added, or removed, and/or that the object itself has been replaced.
* How the object has changed can be determined by examining the
* <tt>NamingEvent</tt>'s old and new bindings.
*<p>
* A listener interested in <tt>OBJECT_CHANGED</tt> event types must:
*<ol>
*
*<li>Implement this interface and its method (<tt>objectChanged()</tt>)
*<li>Implement <tt>NamingListener.namingExceptionThrown()</tt> so that
* it will be notified of exceptions thrown while attempting to
* collect information about the events.
*<li>Register with the source using the source's <tt>addNamingListener()</tt>
* method.
*</ol>
* A listener that wants to be notified of namespace change events
* should also implement the <tt>NamespaceChangeListener</tt>
* interface.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingEvent
* @see NamespaceChangeListener
* @see EventContext
* @see EventDirContext
* @since 1.3
*/
public interface ObjectChangeListener extends NamingListener {
/** {@collect.stats}
* Called when an object has been changed.
*<p>
* The binding of the changed object can be obtained using
* <tt>evt.getNewBinding()</tt>. Its old binding (before the change)
* can be obtained using <tt>evt.getOldBinding()</tt>.
* @param evt The nonnull naming event.
* @see NamingEvent#OBJECT_CHANGED
*/
void objectChanged(NamingEvent evt);
}
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming.event;
/** {@collect.stats}
* This interface is the root of listener interfaces that
* handle <tt>NamingEvent</tt>s.
* It does not make sense for a listener to implement just this interface.
* A listener typically implements a subinterface of <tt>NamingListener</tt>,
* such as <tt>ObjectChangeListener</tt> or <tt>NamespaceChangeListener</tt>.
*<p>
* This interface contains a single method, <tt>namingExceptionThrown()</tt>,
* that must be implemented so that the listener can be notified of
* exceptions that are thrown (by the service provider) while gathering
* information about the events that they're interested in.
* When this method is invoked, the listener has been automatically deregistered
* from the <tt>EventContext</tt> with which it has registered.
*<p>
* For example, suppose a listener implements <tt>ObjectChangeListener</tt> and
* registers with a <tt>EventContext</tt>.
* Then, if the connection to the server is subsequently broken,
* the listener will receive a <tt>NamingExceptionEvent</tt> and may
* take some corrective action, such as notifying the user of the application.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see NamingEvent
* @see NamingExceptionEvent
* @see EventContext
* @see EventDirContext
* @since 1.3
*/
public interface NamingListener extends java.util.EventListener {
/** {@collect.stats}
* Called when a naming exception is thrown while attempting
* to fire a <tt>NamingEvent</tt>.
*
* @param evt The nonnull event.
*/
void namingExceptionThrown(NamingExceptionEvent evt);
}
|
Java
|
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
/** {@collect.stats}
* This exception is used to describe problems encounter while resolving links.
* Addition information is added to the base NamingException for pinpointing
* the problem with the link.
*<p>
* Analogous to how NamingException captures name resolution information,
* LinkException captures "link"-name resolution information pinpointing
* the problem encountered while resolving a link. All these fields may
* be null.
* <ul>
* <li> Link Resolved Name. Portion of link name that has been resolved.
* <li> Link Resolved Object. Object to which resolution of link name proceeded.
* <li> Link Remaining Name. Portion of link name that has not been resolved.
* <li> Link Explanation. Detail explaining why link resolution failed.
*</ul>
*
*<p>
* A LinkException instance is not synchronized against concurrent
* multithreaded access. Multiple threads trying to access and modify
* a single LinkException instance should lock the object.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see Context#lookupLink
* @see LinkRef
* @since 1.3
*/
/*<p>
* The serialized form of a LinkException object consists of the
* serialized fields of its NamingException superclass, the link resolved
* name (a Name object), the link resolved object, link remaining name
* (a Name object), and the link explanation String.
*/
public class LinkException extends NamingException {
/** {@collect.stats}
* Contains the part of the link that has been successfully resolved.
* It is a composite name and can be null.
* This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getLinkResolvedName
* @see #setLinkResolvedName
*/
protected Name linkResolvedName;
/** {@collect.stats}
* Contains the object to which resolution of the part of the link was successful.
* Can be null. This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getLinkResolvedObj
* @see #setLinkResolvedObj
*/
protected Object linkResolvedObj;
/** {@collect.stats}
* Contains the remaining link name that has not been resolved yet.
* It is a composite name and can be null.
* This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getLinkRemainingName
* @see #setLinkRemainingName
*/
protected Name linkRemainingName;
/** {@collect.stats}
* Contains the exception of why resolution of the link failed.
* Can be null. This field is initialized by the constructors.
* You should access and manipulate this field
* through its get and set methods.
* @serial
* @see #getLinkExplanation
* @see #setLinkExplanation
*/
protected String linkExplanation;
/** {@collect.stats}
* Constructs a new instance of LinkException with an explanation
* All the other fields are initialized to null.
* @param explanation A possibly null string containing additional
* detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public LinkException(String explanation) {
super(explanation);
linkResolvedName = null;
linkResolvedObj = null;
linkRemainingName = null;
linkExplanation = null;
}
/** {@collect.stats}
* Constructs a new instance of LinkException.
* All the non-link-related and link-related fields are initialized to null.
*/
public LinkException() {
super();
linkResolvedName = null;
linkResolvedObj = null;
linkRemainingName = null;
linkExplanation = null;
}
/** {@collect.stats}
* Retrieves the leading portion of the link name that was resolved
* successfully.
*
* @return The part of the link name that was resolved successfully.
* It is a composite name. It can be null, which means
* the link resolved name field has not been set.
* @see #getLinkResolvedObj
* @see #setLinkResolvedName
*/
public Name getLinkResolvedName() {
return this.linkResolvedName;
}
/** {@collect.stats}
* Retrieves the remaining unresolved portion of the link name.
* @return The part of the link name that has not been resolved.
* It is a composite name. It can be null, which means
* the link remaining name field has not been set.
* @see #setLinkRemainingName
*/
public Name getLinkRemainingName() {
return this.linkRemainingName;
}
/** {@collect.stats}
* Retrieves the object to which resolution was successful.
* This is the object to which the resolved link name is bound.
*
* @return The possibly null object that was resolved so far.
* If null, it means the link resolved object field has not been set.
* @see #getLinkResolvedName
* @see #setLinkResolvedObj
*/
public Object getLinkResolvedObj() {
return this.linkResolvedObj;
}
/** {@collect.stats}
* Retrieves the explanation associated with the problem encounter
* when resolving a link.
*
* @return The possibly null detail string explaining more about the problem
* with resolving a link.
* If null, it means there is no
* link detail message for this exception.
* @see #setLinkExplanation
*/
public String getLinkExplanation() {
return this.linkExplanation;
}
/** {@collect.stats}
* Sets the explanation associated with the problem encounter
* when resolving a link.
*
* @param msg The possibly null detail string explaining more about the problem
* with resolving a link. If null, it means no detail will be recorded.
* @see #getLinkExplanation
*/
public void setLinkExplanation(String msg) {
this.linkExplanation = msg;
}
/** {@collect.stats}
* Sets the resolved link name field of this exception.
*<p>
* <tt>name</tt> is a composite name. If the intent is to set
* this field using a compound name or string, you must
* "stringify" the compound name, and create a composite
* name with a single component using the string. You can then
* invoke this method using the resulting composite name.
*<p>
* A copy of <code>name</code> is made and stored.
* Subsequent changes to <code>name</code> does not
* affect the copy in this NamingException and vice versa.
*
*
* @param name The name to set resolved link name to. This can be null.
* If null, it sets the link resolved name field to null.
* @see #getLinkResolvedName
*/
public void setLinkResolvedName(Name name) {
if (name != null) {
this.linkResolvedName = (Name)(name.clone());
} else {
this.linkResolvedName = null;
}
}
/** {@collect.stats}
* Sets the remaining link name field of this exception.
*<p>
* <tt>name</tt> is a composite name. If the intent is to set
* this field using a compound name or string, you must
* "stringify" the compound name, and create a composite
* name with a single component using the string. You can then
* invoke this method using the resulting composite name.
*<p>
* A copy of <code>name</code> is made and stored.
* Subsequent changes to <code>name</code> does not
* affect the copy in this NamingException and vice versa.
*
* @param name The name to set remaining link name to. This can be null.
* If null, it sets the remaining name field to null.
* @see #getLinkRemainingName
*/
public void setLinkRemainingName(Name name) {
if (name != null)
this.linkRemainingName = (Name)(name.clone());
else
this.linkRemainingName = null;
}
/** {@collect.stats}
* Sets the link resolved object field of this exception.
* This indicates the last successfully resolved object of link name.
* @param obj The object to set link resolved object to. This can be null.
* If null, the link resolved object field is set to null.
* @see #getLinkResolvedObj
*/
public void setLinkResolvedObj(Object obj) {
this.linkResolvedObj = obj;
}
/** {@collect.stats}
* Generates the string representation of this exception.
* This string consists of the NamingException information plus
* the link's remaining name.
* This string is used for debugging and not meant to be interpreted
* programmatically.
* @return The non-null string representation of this link exception.
*/
public String toString() {
return super.toString() + "; Link Remaining Name: '" +
this.linkRemainingName + "'";
}
/** {@collect.stats}
* Generates the string representation of this exception.
* This string consists of the NamingException information plus
* the additional information of resolving the link.
* If 'detail' is true, the string also contains information on
* the link resolved object. If false, this method is the same
* as the form of toString() that accepts no parameters.
* This string is used for debugging and not meant to be interpreted
* programmatically.
*
* @param detail If true, add information about the link resolved
* object.
* @return The non-null string representation of this link exception.
*/
public String toString(boolean detail) {
if (!detail || this.linkResolvedObj == null)
return this.toString();
return this.toString() + "; Link Resolved Object: " +
this.linkResolvedObj;
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -7967662604076777712L;
};
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
import javax.naming.Name;
/** {@collect.stats}
* This exception is thrown when a method
* does not terminate within the specified time limit.
* This can happen, for example, if the user specifies that
* the method should take no longer than 10 seconds, and the
* method fails to complete with 10 seconds.
*
* <p> Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @since 1.3
*/
public class TimeLimitExceededException extends LimitExceededException {
/** {@collect.stats}
* Constructs a new instance of TimeLimitExceededException.
* All fields default to null.
*/
public TimeLimitExceededException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of TimeLimitExceededException
* using the argument supplied.
* @param explanation possibly null detail about this exception.
* @see java.lang.Throwable#getMessage
*/
public TimeLimitExceededException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = -3597009011385034696L;
}
|
Java
|
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
import java.util.Hashtable;
/** {@collect.stats}
* This interface represents a naming context, which
* consists of a set of name-to-object bindings.
* It contains methods for examining and updating these bindings.
* <p>
* <h4>Names</h4>
* Each name passed as an argument to a <tt>Context</tt> method is relative
* to that context. The empty name is used to name the context itself.
* A name parameter may never be null.
* <p>
* Most of the methods have overloaded versions with one taking a
* <code>Name</code> parameter and one taking a <code>String</code>.
* These overloaded versions are equivalent in that if
* the <code>Name</code> and <code>String</code> parameters are just
* different representations of the same name, then the overloaded
* versions of the same methods behave the same.
* In the method descriptions below, only one version is fully documented.
* The second version instead has a link to the first: the same
* documentation applies to both.
* <p>
* For systems that support federation, <tt>String</tt> name arguments to
* <tt>Context</tt> methods are composite names. Name arguments that are
* instances of <tt>CompositeName</tt> are treated as composite names,
* while <tt>Name</tt> arguments that are not instances of
* <tt>CompositeName</tt> are treated as compound names (which might be
* instances of <tt>CompoundName</tt> or other implementations of compound
* names). This allows the results of <tt>NameParser.parse()</tt> to be used as
* arguments to the <tt>Context</tt> methods.
* Prior to JNDI 1.2, all name arguments were treated as composite names.
*<p>
* Furthermore, for systems that support federation, all names returned
* in a <tt>NamingEnumeration</tt>
* from <tt>list()</tt> and <tt>listBindings()</tt> are composite names
* represented as strings.
* See <tt>CompositeName</tt> for the string syntax of names.
*<p>
* For systems that do not support federation, the name arguments (in
* either <tt>Name</tt> or <tt>String</tt> forms) and the names returned in
* <tt>NamingEnumeration</tt> may be names in their own namespace rather than
* names in a composite namespace, at the discretion of the service
* provider.
*<p>
*<h4>Exceptions</h4>
* All the methods in this interface can throw a <tt>NamingException</tt> or
* any of its subclasses. See <tt>NamingException</tt> and their subclasses
* for details on each exception.
*<p>
*<h4>Concurrent Access</h4>
* A Context instance is not guaranteed to be synchronized against
* concurrent access by multiple threads. Threads that need to access
* a single Context instance concurrently should synchronize amongst
* themselves and provide the necessary locking. Multiple threads
* each manipulating a different Context instance need not
* synchronize. Note that the {@link #lookup(Name) <tt>lookup</tt>}
* method, when passed an empty name, will return a new Context instance
* representing the same naming context.
*<p>
* For purposes of concurrency control,
* a Context operation that returns a <tt>NamingEnumeration</tt> is
* not considered to have completed while the enumeration is still in
* use, or while any referrals generated by that operation are still
* being followed.
*
*<p>
*<h4>Parameters</h4>
* A <tt>Name</tt> parameter passed to any method of the
* <tt>Context</tt> interface or one of its subinterfaces
* will not be modified by the service provider.
* The service provider may keep a reference to it
* for the duration of the operation, including any enumeration of the
* method's results and the processing of any referrals generated.
* The caller should not modify the object during this time.
* A <tt>Name</tt> returned by any such method is owned by the caller.
* The caller may subsequently modify it; the service provider may not.
*
*<p>
*<h4>Environment Properties</h4>
*<p>
* JNDI applications need a way to communicate various preferences
* and properties that define the environment in which naming and
* directory services are accessed. For example, a context might
* require specification of security credentials in order to access
* the service. Another context might require that server configuration
* information be supplied. These are referred to as the <em>environment</em>
* of a context. The <tt>Context</tt> interface provides methods for
* retrieving and updating this environment.
*<p>
* The environment is inherited from the parent context as
* context methods proceed from one context to the next. Changes to
* the environment of one context do not directly affect those
* of other contexts.
*<p>
* It is implementation-dependent when environment properties are used
* and/or verified for validity. For example, some of the
* security-related properties are used by service providers to "log in"
* to the directory. This login process might occur at the time the
* context is created, or the first time a method is invoked on the
* context. When, and whether this occurs at all, is
* implementation-dependent. When environment properties are added or
* removed from the context, verifying the validity of the changes is again
* implementation-dependent. For example, verification of some properties
* might occur at the time the change is made, or at the time the next
* operation is performed on the context, or not at all.
*<p>
* Any object with a reference to a context may examine that context's
* environment. Sensitive information such as clear-text
* passwords should not be stored there unless the implementation is
* known to protect it.
*
*<p>
*<a name=RESOURCEFILES></a>
*<h4>Resource Files</h4>
*<p>
* To simplify the task of setting up the environment
* required by a JNDI application,
* application components and service providers may be distributed
* along with <em>resource files.</em>
* A JNDI resource file is a file in the properties file format (see
* {@link java.util.Properties#load <tt>java.util.Properties</tt>}),
* containing a list of key/value pairs.
* The key is the name of the property (e.g. "java.naming.factory.object")
* and the value is a string in the format defined
* for that property. Here is an example of a JNDI resource file:
*
* <blockquote><tt><pre>
* java.naming.factory.object=com.sun.jndi.ldap.AttrsToCorba:com.wiz.from.Person
* java.naming.factory.state=com.sun.jndi.ldap.CorbaToAttrs:com.wiz.from.Person
* java.naming.factory.control=com.sun.jndi.ldap.ResponseControlFactory
* </pre></tt></blockquote>
*
* The JNDI class library reads the resource files and makes the property
* values freely available. Thus JNDI resource files should be considered
* to be "world readable", and sensitive information such as clear-text
* passwords should not be stored there.
*<p>
* There are two kinds of JNDI resource files:
* <em>provider</em> and <em>application</em>.
*
* <h5>Provider Resource Files</h5>
*
* Each service provider has an optional resource that lists properties
* specific to that provider. The name of this resource is:
* <blockquote>
* [<em>prefix</em>/]<tt>jndiprovider.properties</tt>
* </blockquote>
* where <em>prefix</em> is
* the package name of the provider's context implementation(s),
* with each period (".") converted to a slash ("/").
*
* For example, suppose a service provider defines a context
* implementation with class name <tt>com.sun.jndi.ldap.LdapCtx</tt>.
* The provider resource for this provider is named
* <tt>com/sun/jndi/ldap/jndiprovider.properties</tt>. If the class is
* not in a package, the resource's name is simply
* <tt>jndiprovider.properties</tt>.
*
* <p>
* <a name=LISTPROPS></a>
* Certain methods in the JNDI class library make use of the standard
* JNDI properties that specify lists of JNDI factories:
* <ul>
* <li>java.naming.factory.object
* <li>java.naming.factory.state
* <li>java.naming.factory.control
* <li>java.naming.factory.url.pkgs
* </ul>
* The JNDI library will consult the provider resource file
* when determining the values of these properties.
* Properties other than these may be set in the provider
* resource file at the discretion of the service provider.
* The service provider's documentation should clearly state which
* properties are allowed; other properties in the file will be ignored.
*
* <h5>Application Resource Files</h5>
*
* When an application is deployed, it will generally have several
* codebase directories and JARs in its classpath. Similarly, when an
* applet is deployed, it will have a codebase and archives specifying
* where to find the applet's classes. JNDI locates (using
* {@link ClassLoader#getResources <tt>ClassLoader.getResources()</tt>})
* all <em>application resource files</em> named <tt>jndi.properties</tt>
* in the classpath.
* In addition, if the file <i>java.home</i><tt>/lib/jndi.properties</tt>
* exists and is readable,
* JNDI treats it as an additional application resource file.
* (<i>java.home</i> indicates the
* directory named by the <tt>java.home</tt> system property.)
* All of the properties contained in these files are placed
* into the environment of the initial context. This environment
* is then inherited by other contexts.
*
* <p>
* For each property found in more than one application resource file,
* JNDI uses the first value found or, in a few cases where it makes
* sense to do so, it concatenates all of the values (details are given
* below).
* For example, if the "java.naming.factory.object" property is found in
* three <tt>jndi.properties</tt> resource files, the
* list of object factories is a concatenation of the property
* values from all three files.
* Using this scheme, each deployable component is responsible for
* listing the factories that it exports. JNDI automatically
* collects and uses all of these export lists when searching for factory
* classes.
*
* <h5>Search Algorithm for Properties</h5>
*
* When JNDI constructs an initial context, the context's environment
* is initialized with properties defined in the environment parameter
* passed to the constructor, the system properties, the applet parameters,
* and the application resource files. See
* <a href=InitialContext.html#ENVIRONMENT><tt>InitialContext</tt></a>
* for details.
* This initial environment is then inherited by other context instances.
*
* <p>
* When the JNDI class library needs to determine
* the value of a property, it does so by merging
* the values from the following two sources, in order:
* <ol>
* <li>The environment of the context being operated on.
* <li>The provider resource file (<tt>jndiprovider.properties</tt>)
* for the context being operated on.
* </ol>
* For each property found in both of these two sources,
* JNDI determines the property's value as follows. If the property is
* one of the standard JNDI properties that specify a list of JNDI
* factories (listed <a href=#LISTPROPS>above</a>), the values are
* concatenated into a single colon-separated list. For other
* properties, only the first value found is used.
*
* <p>
* When a service provider needs to determine the value of a property,
* it will generally take that value directly from the environment.
* A service provider may define provider-specific properties
* to be placed in its own provider resource file. In that
* case it should merge values as described in the previous paragraph.
*
* <p>
* In this way, each service provider developer can specify a list of
* factories to use with that service provider. These can be modified by
* the application resources specified by the deployer of the application
* or applet, which in turn can be modified by the user.
*
* @author Rosanna Lee
* @author Scott Seligman
* @author R. Vasudevan
*
* @since 1.3
*/
public interface Context {
/** {@collect.stats}
* Retrieves the named object.
* If <tt>name</tt> is empty, returns a new instance of this context
* (which represents the same naming context as this context, but its
* environment may be modified independently and it may be accessed
* concurrently).
*
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>
* @throws NamingException if a naming exception is encountered
*
* @see #lookup(String)
* @see #lookupLink(Name)
*/
public Object lookup(Name name) throws NamingException;
/** {@collect.stats}
* Retrieves the named object.
* See {@link #lookup(Name)} for details.
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>
* @throws NamingException if a naming exception is encountered
*/
public Object lookup(String name) throws NamingException;
/** {@collect.stats}
* Binds a name to an object.
* All intermediate contexts and the target context (that named by all
* but terminal atomic component of the name) must already exist.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @throws NameAlreadyBoundException if name is already bound
* @throws javax.naming.directory.InvalidAttributesException
* if object did not supply all mandatory attributes
* @throws NamingException if a naming exception is encountered
*
* @see #bind(String, Object)
* @see #rebind(Name, Object)
* @see javax.naming.directory.DirContext#bind(Name, Object,
* javax.naming.directory.Attributes)
*/
public void bind(Name name, Object obj) throws NamingException;
/** {@collect.stats}
* Binds a name to an object.
* See {@link #bind(Name, Object)} for details.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @throws NameAlreadyBoundException if name is already bound
* @throws javax.naming.directory.InvalidAttributesException
* if object did not supply all mandatory attributes
* @throws NamingException if a naming exception is encountered
*/
public void bind(String name, Object obj) throws NamingException;
/** {@collect.stats}
* Binds a name to an object, overwriting any existing binding.
* All intermediate contexts and the target context (that named by all
* but terminal atomic component of the name) must already exist.
*
* <p> If the object is a <tt>DirContext</tt>, any existing attributes
* associated with the name are replaced with those of the object.
* Otherwise, any existing attributes associated with the name remain
* unchanged.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @throws javax.naming.directory.InvalidAttributesException
* if object did not supply all mandatory attributes
* @throws NamingException if a naming exception is encountered
*
* @see #rebind(String, Object)
* @see #bind(Name, Object)
* @see javax.naming.directory.DirContext#rebind(Name, Object,
* javax.naming.directory.Attributes)
* @see javax.naming.directory.DirContext
*/
public void rebind(Name name, Object obj) throws NamingException;
/** {@collect.stats}
* Binds a name to an object, overwriting any existing binding.
* See {@link #rebind(Name, Object)} for details.
*
* @param name
* the name to bind; may not be empty
* @param obj
* the object to bind; possibly null
* @throws javax.naming.directory.InvalidAttributesException
* if object did not supply all mandatory attributes
* @throws NamingException if a naming exception is encountered
*/
public void rebind(String name, Object obj) throws NamingException;
/** {@collect.stats}
* Unbinds the named object.
* Removes the terminal atomic name in <code>name</code>
* from the target context--that named by all but the terminal
* atomic part of <code>name</code>.
*
* <p> This method is idempotent.
* It succeeds even if the terminal atomic name
* is not bound in the target context, but throws
* <tt>NameNotFoundException</tt>
* if any of the intermediate contexts do not exist.
*
* <p> Any attributes associated with the name are removed.
* Intermediate contexts are not changed.
*
* @param name
* the name to unbind; may not be empty
* @throws NameNotFoundException if an intermediate context does not exist
* @throws NamingException if a naming exception is encountered
* @see #unbind(String)
*/
public void unbind(Name name) throws NamingException;
/** {@collect.stats}
* Unbinds the named object.
* See {@link #unbind(Name)} for details.
*
* @param name
* the name to unbind; may not be empty
* @throws NameNotFoundException if an intermediate context does not exist
* @throws NamingException if a naming exception is encountered
*/
public void unbind(String name) throws NamingException;
/** {@collect.stats}
* Binds a new name to the object bound to an old name, and unbinds
* the old name. Both names are relative to this context.
* Any attributes associated with the old name become associated
* with the new name.
* Intermediate contexts of the old name are not changed.
*
* @param oldName
* the name of the existing binding; may not be empty
* @param newName
* the name of the new binding; may not be empty
* @throws NameAlreadyBoundException if <tt>newName</tt> is already bound
* @throws NamingException if a naming exception is encountered
*
* @see #rename(String, String)
* @see #bind(Name, Object)
* @see #rebind(Name, Object)
*/
public void rename(Name oldName, Name newName) throws NamingException;
/** {@collect.stats}
* Binds a new name to the object bound to an old name, and unbinds
* the old name.
* See {@link #rename(Name, Name)} for details.
*
* @param oldName
* the name of the existing binding; may not be empty
* @param newName
* the name of the new binding; may not be empty
* @throws NameAlreadyBoundException if <tt>newName</tt> is already bound
* @throws NamingException if a naming exception is encountered
*/
public void rename(String oldName, String newName) throws NamingException;
/** {@collect.stats}
* Enumerates the names bound in the named context, along with the
* class names of objects bound to them.
* The contents of any subcontexts are not included.
*
* <p> If a binding is added to or removed from this context,
* its effect on an enumeration previously returned is undefined.
*
* @param name
* the name of the context to list
* @return an enumeration of the names and class names of the
* bindings in this context. Each element of the
* enumeration is of type <tt>NameClassPair</tt>.
* @throws NamingException if a naming exception is encountered
*
* @see #list(String)
* @see #listBindings(Name)
* @see NameClassPair
*/
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException;
/** {@collect.stats}
* Enumerates the names bound in the named context, along with the
* class names of objects bound to them.
* See {@link #list(Name)} for details.
*
* @param name
* the name of the context to list
* @return an enumeration of the names and class names of the
* bindings in this context. Each element of the
* enumeration is of type <tt>NameClassPair</tt>.
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException;
/** {@collect.stats}
* Enumerates the names bound in the named context, along with the
* objects bound to them.
* The contents of any subcontexts are not included.
*
* <p> If a binding is added to or removed from this context,
* its effect on an enumeration previously returned is undefined.
*
* @param name
* the name of the context to list
* @return an enumeration of the bindings in this context.
* Each element of the enumeration is of type
* <tt>Binding</tt>.
* @throws NamingException if a naming exception is encountered
*
* @see #listBindings(String)
* @see #list(Name)
* @see Binding
*/
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException;
/** {@collect.stats}
* Enumerates the names bound in the named context, along with the
* objects bound to them.
* See {@link #listBindings(Name)} for details.
*
* @param name
* the name of the context to list
* @return an enumeration of the bindings in this context.
* Each element of the enumeration is of type
* <tt>Binding</tt>.
* @throws NamingException if a naming exception is encountered
*/
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException;
/** {@collect.stats}
* Destroys the named context and removes it from the namespace.
* Any attributes associated with the name are also removed.
* Intermediate contexts are not destroyed.
*
* <p> This method is idempotent.
* It succeeds even if the terminal atomic name
* is not bound in the target context, but throws
* <tt>NameNotFoundException</tt>
* if any of the intermediate contexts do not exist.
*
* <p> In a federated naming system, a context from one naming system
* may be bound to a name in another. One can subsequently
* look up and perform operations on the foreign context using a
* composite name. However, an attempt destroy the context using
* this composite name will fail with
* <tt>NotContextException</tt>, because the foreign context is not
* a "subcontext" of the context in which it is bound.
* Instead, use <tt>unbind()</tt> to remove the
* binding of the foreign context. Destroying the foreign context
* requires that the <tt>destroySubcontext()</tt> be performed
* on a context from the foreign context's "native" naming system.
*
* @param name
* the name of the context to be destroyed; may not be empty
* @throws NameNotFoundException if an intermediate context does not exist
* @throws NotContextException if the name is bound but does not name a
* context, or does not name a context of the appropriate type
* @throws ContextNotEmptyException if the named context is not empty
* @throws NamingException if a naming exception is encountered
*
* @see #destroySubcontext(String)
*/
public void destroySubcontext(Name name) throws NamingException;
/** {@collect.stats}
* Destroys the named context and removes it from the namespace.
* See {@link #destroySubcontext(Name)} for details.
*
* @param name
* the name of the context to be destroyed; may not be empty
* @throws NameNotFoundException if an intermediate context does not exist
* @throws NotContextException if the name is bound but does not name a
* context, or does not name a context of the appropriate type
* @throws ContextNotEmptyException if the named context is not empty
* @throws NamingException if a naming exception is encountered
*/
public void destroySubcontext(String name) throws NamingException;
/** {@collect.stats}
* Creates and binds a new context.
* Creates a new context with the given name and binds it in
* the target context (that named by all but terminal atomic
* component of the name). All intermediate contexts and the
* target context must already exist.
*
* @param name
* the name of the context to create; may not be empty
* @return the newly created context
*
* @throws NameAlreadyBoundException if name is already bound
* @throws javax.naming.directory.InvalidAttributesException
* if creation of the subcontext requires specification of
* mandatory attributes
* @throws NamingException if a naming exception is encountered
*
* @see #createSubcontext(String)
* @see javax.naming.directory.DirContext#createSubcontext
*/
public Context createSubcontext(Name name) throws NamingException;
/** {@collect.stats}
* Creates and binds a new context.
* See {@link #createSubcontext(Name)} for details.
*
* @param name
* the name of the context to create; may not be empty
* @return the newly created context
*
* @throws NameAlreadyBoundException if name is already bound
* @throws javax.naming.directory.InvalidAttributesException
* if creation of the subcontext requires specification of
* mandatory attributes
* @throws NamingException if a naming exception is encountered
*/
public Context createSubcontext(String name) throws NamingException;
/** {@collect.stats}
* Retrieves the named object, following links except
* for the terminal atomic component of the name.
* If the object bound to <tt>name</tt> is not a link,
* returns the object itself.
*
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>, not following the
* terminal link (if any).
* @throws NamingException if a naming exception is encountered
*
* @see #lookupLink(String)
*/
public Object lookupLink(Name name) throws NamingException;
/** {@collect.stats}
* Retrieves the named object, following links except
* for the terminal atomic component of the name.
* See {@link #lookupLink(Name)} for details.
*
* @param name
* the name of the object to look up
* @return the object bound to <tt>name</tt>, not following the
* terminal link (if any)
* @throws NamingException if a naming exception is encountered
*/
public Object lookupLink(String name) throws NamingException;
/** {@collect.stats}
* Retrieves the parser associated with the named context.
* In a federation of namespaces, different naming systems will
* parse names differently. This method allows an application
* to get a parser for parsing names into their atomic components
* using the naming convention of a particular naming system.
* Within any single naming system, <tt>NameParser</tt> objects
* returned by this method must be equal (using the <tt>equals()</tt>
* test).
*
* @param name
* the name of the context from which to get the parser
* @return a name parser that can parse compound names into their atomic
* components
* @throws NamingException if a naming exception is encountered
*
* @see #getNameParser(String)
* @see CompoundName
*/
public NameParser getNameParser(Name name) throws NamingException;
/** {@collect.stats}
* Retrieves the parser associated with the named context.
* See {@link #getNameParser(Name)} for details.
*
* @param name
* the name of the context from which to get the parser
* @return a name parser that can parse compound names into their atomic
* components
* @throws NamingException if a naming exception is encountered
*/
public NameParser getNameParser(String name) throws NamingException;
/** {@collect.stats}
* Composes the name of this context with a name relative to
* this context.
* Given a name (<code>name</code>) relative to this context, and
* the name (<code>prefix</code>) of this context relative to one
* of its ancestors, this method returns the composition of the
* two names using the syntax appropriate for the naming
* system(s) involved. That is, if <code>name</code> names an
* object relative to this context, the result is the name of the
* same object, but relative to the ancestor context. None of the
* names may be null.
* <p>
* For example, if this context is named "wiz.com" relative
* to the initial context, then
* <pre>
* composeName("east", "wiz.com") </pre>
* might return <code>"east.wiz.com"</code>.
* If instead this context is named "org/research", then
* <pre>
* composeName("user/jane", "org/research") </pre>
* might return <code>"org/research/user/jane"</code> while
* <pre>
* composeName("user/jane", "research") </pre>
* returns <code>"research/user/jane"</code>.
*
* @param name
* a name relative to this context
* @param prefix
* the name of this context relative to one of its ancestors
* @return the composition of <code>prefix</code> and <code>name</code>
* @throws NamingException if a naming exception is encountered
*
* @see #composeName(String, String)
*/
public Name composeName(Name name, Name prefix)
throws NamingException;
/** {@collect.stats}
* Composes the name of this context with a name relative to
* this context.
* See {@link #composeName(Name, Name)} for details.
*
* @param name
* a name relative to this context
* @param prefix
* the name of this context relative to one of its ancestors
* @return the composition of <code>prefix</code> and <code>name</code>
* @throws NamingException if a naming exception is encountered
*/
public String composeName(String name, String prefix)
throws NamingException;
/** {@collect.stats}
* Adds a new environment property to the environment of this
* context. If the property already exists, its value is overwritten.
* See class description for more details on environment properties.
*
* @param propName
* the name of the environment property to add; may not be null
* @param propVal
* the value of the property to add; may not be null
* @return the previous value of the property, or null if the property was
* not in the environment before
* @throws NamingException if a naming exception is encountered
*
* @see #getEnvironment()
* @see #removeFromEnvironment(String)
*/
public Object addToEnvironment(String propName, Object propVal)
throws NamingException;
/** {@collect.stats}
* Removes an environment property from the environment of this
* context. See class description for more details on environment
* properties.
*
* @param propName
* the name of the environment property to remove; may not be null
* @return the previous value of the property, or null if the property was
* not in the environment
* @throws NamingException if a naming exception is encountered
*
* @see #getEnvironment()
* @see #addToEnvironment(String, Object)
*/
public Object removeFromEnvironment(String propName)
throws NamingException;
/** {@collect.stats}
* Retrieves the environment in effect for this context.
* See class description for more details on environment properties.
*
* <p> The caller should not make any changes to the object returned:
* their effect on the context is undefined.
* The environment of this context may be changed using
* <tt>addToEnvironment()</tt> and <tt>removeFromEnvironment()</tt>.
*
* @return the environment of this context; never null
* @throws NamingException if a naming exception is encountered
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
public Hashtable<?,?> getEnvironment() throws NamingException;
/** {@collect.stats}
* Closes this context.
* This method releases this context's resources immediately, instead of
* waiting for them to be released automatically by the garbage collector.
*
* <p> This method is idempotent: invoking it on a context that has
* already been closed has no effect. Invoking any other method
* on a closed context is not allowed, and results in undefined behaviour.
*
* @throws NamingException if a naming exception is encountered
*/
public void close() throws NamingException;
/** {@collect.stats}
* Retrieves the full name of this context within its own namespace.
*
* <p> Many naming services have a notion of a "full name" for objects
* in their respective namespaces. For example, an LDAP entry has
* a distinguished name, and a DNS record has a fully qualified name.
* This method allows the client application to retrieve this name.
* The string returned by this method is not a JNDI composite name
* and should not be passed directly to context methods.
* In naming systems for which the notion of full name does not
* make sense, <tt>OperationNotSupportedException</tt> is thrown.
*
* @return this context's name in its own namespace; never null
* @throws OperationNotSupportedException if the naming system does
* not have the notion of a full name
* @throws NamingException if a naming exception is encountered
*
* @since 1.3
*/
public String getNameInNamespace() throws NamingException;
// public static final: JLS says recommended style is to omit these modifiers
// because they are the default
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the initial context factory to use. The value
* of the property should be the fully qualified class name
* of the factory class that will create an initial context.
* This property may be specified in the environment parameter
* passed to the initial context constructor, an applet parameter,
* a system property, or an application resource file.
* If it is not specified in any of these sources,
* <tt>NoInitialContextException</tt> is thrown when an initial
* context is required to complete an operation.
*
* <p> The value of this constant is "java.naming.factory.initial".
*
* @see InitialContext
* @see javax.naming.directory.InitialDirContext
* @see javax.naming.spi.NamingManager#getInitialContext
* @see javax.naming.spi.InitialContextFactory
* @see NoInitialContextException
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see #APPLET
*/
String INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial";
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the list of object factories to use. The value
* of the property should be a colon-separated list of the fully
* qualified class names of factory classes that will create an object
* given information about the object.
* This property may be specified in the environment, an applet
* parameter, a system property, or one or more resource files.
*
* <p> The value of this constant is "java.naming.factory.object".
*
* @see javax.naming.spi.NamingManager#getObjectInstance
* @see javax.naming.spi.ObjectFactory
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see #APPLET
*/
String OBJECT_FACTORIES = "java.naming.factory.object";
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the list of state factories to use. The value
* of the property should be a colon-separated list of the fully
* qualified class names of state factory classes that will be used
* to get an object's state given the object itself.
* This property may be specified in the environment, an applet
* parameter, a system property, or one or more resource files.
*
* <p> The value of this constant is "java.naming.factory.state".
*
* @see javax.naming.spi.NamingManager#getStateToBind
* @see javax.naming.spi.StateFactory
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see #APPLET
* @since 1.3
*/
String STATE_FACTORIES = "java.naming.factory.state";
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the list of package prefixes to use when
* loading in URL context factories. The value
* of the property should be a colon-separated list of package
* prefixes for the class name of the factory class that will create
* a URL context factory.
* This property may be specified in the environment,
* an applet parameter, a system property, or one or more
* resource files.
* The prefix <tt>com.sun.jndi.url</tt> is always appended to
* the possibly empty list of package prefixes.
*
* <p> The value of this constant is "java.naming.factory.url.pkgs".
*
* @see javax.naming.spi.NamingManager#getObjectInstance
* @see javax.naming.spi.NamingManager#getURLContext
* @see javax.naming.spi.ObjectFactory
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see #APPLET
*/
String URL_PKG_PREFIXES = "java.naming.factory.url.pkgs";
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying configuration information for the service provider
* to use. The value of the property should contain a URL string
* (e.g. "ldap://somehost:389").
* This property may be specified in the environment,
* an applet parameter, a system property, or a resource file.
* If it is not specified in any of these sources,
* the default configuration is determined by the service provider.
*
* <p> The value of this constant is "java.naming.provider.url".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see #APPLET
*/
String PROVIDER_URL = "java.naming.provider.url";
/** {@collect.stats}
* Constant that holds the name of the environment property
* for specifying the DNS host and domain names to use for the
* JNDI URL context (for example, "dns://somehost/wiz.com").
* This property may be specified in the environment,
* an applet parameter, a system property, or a resource file.
* If it is not specified in any of these sources
* and the program attempts to use a JNDI URL containing a DNS name,
* a <tt>ConfigurationException</tt> will be thrown.
*
* <p> The value of this constant is "java.naming.dns.url".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String DNS_URL = "java.naming.dns.url";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the authoritativeness of the service requested.
* If the value of the property is the string "true", it means
* that the access is to the most authoritative source (i.e. bypass
* any cache or replicas). If the value is anything else,
* the source need not be (but may be) authoritative.
* If unspecified, the value defaults to "false".
*
* <p> The value of this constant is "java.naming.authoritative".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String AUTHORITATIVE = "java.naming.authoritative";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the batch size to use when returning data via the
* service's protocol. This is a hint to the provider to return
* the results of operations in batches of the specified size, so
* the provider can optimize its performance and usage of resources.
* The value of the property is the string representation of an
* integer.
* If unspecified, the batch size is determined by the service
* provider.
*
* <p> The value of this constant is "java.naming.batchsize".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String BATCHSIZE = "java.naming.batchsize";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying how referrals encountered by the service provider
* are to be processed. The value of the property is one of the
* following strings:
* <dl>
* <dt>"follow"
* <dd>follow referrals automatically
* <dt>"ignore"
* <dd>ignore referrals
* <dt>"throw"
* <dd>throw <tt>ReferralException</tt> when a referral is encountered.
* </dl>
* If this property is not specified, the default is
* determined by the provider.
*
* <p> The value of this constant is "java.naming.referral".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String REFERRAL = "java.naming.referral";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the security protocol to use.
* Its value is a string determined by the service provider
* (e.g. "ssl").
* If this property is unspecified,
* the behaviour is determined by the service provider.
*
* <p> The value of this constant is "java.naming.security.protocol".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String SECURITY_PROTOCOL = "java.naming.security.protocol";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the security level to use.
* Its value is one of the following strings:
* "none", "simple", "strong".
* If this property is unspecified,
* the behaviour is determined by the service provider.
*
* <p> The value of this constant is "java.naming.security.authentication".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String SECURITY_AUTHENTICATION = "java.naming.security.authentication";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the identity of the principal for authenticating
* the caller to the service. The format of the principal
* depends on the authentication scheme.
* If this property is unspecified,
* the behaviour is determined by the service provider.
*
* <p> The value of this constant is "java.naming.security.principal".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String SECURITY_PRINCIPAL = "java.naming.security.principal";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the credentials of the principal for authenticating
* the caller to the service. The value of the property depends
* on the authentication scheme. For example, it could be a hashed
* password, clear-text password, key, certificate, and so on.
* If this property is unspecified,
* the behaviour is determined by the service provider.
*
* <p> The value of this constant is "java.naming.security.credentials".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String SECURITY_CREDENTIALS = "java.naming.security.credentials";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying the preferred language to use with the service.
* The value of the property is a colon-separated list of language
* tags as defined in RFC 1766.
* If this property is unspecified,
* the language preference is determined by the service provider.
*
* <p> The value of this constant is "java.naming.language".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
*/
String LANGUAGE = "java.naming.language";
/** {@collect.stats}
* Constant that holds the name of the environment property for
* specifying an applet for the initial context constructor to use
* when searching for other properties.
* The value of this property is the
* <tt>java.applet.Applet</tt> instance that is being executed.
* This property may be specified in the environment parameter
* passed to the initial context constructor.
* When this property is set, each property that the initial context
* constructor looks for in the system properties is first looked for
* in the applet's parameter list.
* If this property is unspecified, the initial context constructor
* will search for properties only in the environment parameter
* passed to it, the system properties, and application resource files.
*
* <p> The value of this constant is "java.naming.applet".
*
* @see #addToEnvironment(String, Object)
* @see #removeFromEnvironment(String)
* @see InitialContext
*
* @since 1.3
*/
String APPLET = "java.naming.applet";
};
|
Java
|
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.naming;
import javax.naming.Name;
/** {@collect.stats}
* This exception is thrown when a method
* produces a result that exceeds a size-related limit.
* This can happen, for example, if the result contains
* more objects than the user requested, or when the size
* of the result exceeds some implementation-specific limit.
* <p>
* Synchronization and serialization issues that apply to NamingException
* apply directly here.
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @since 1.3
*/
public class SizeLimitExceededException extends LimitExceededException {
/** {@collect.stats}
* Constructs a new instance of SizeLimitExceededException.
* All fields default to null.
*/
public SizeLimitExceededException() {
super();
}
/** {@collect.stats}
* Constructs a new instance of SizeLimitExceededException using an
* explanation. All other fields default to null.
*
* @param explanation Possibly null detail about this exception.
*/
public SizeLimitExceededException(String explanation) {
super(explanation);
}
/** {@collect.stats}
* Use serialVersionUID from JNDI 1.1.1 for interoperability
*/
private static final long serialVersionUID = 7129289564879168579L;
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.