From 6b811c5daec1b28e6f63b57f98a032236f2c3cf7 Mon Sep 17 00:00:00 2001
From: Peter Hallam COPYRIGHT AND PERMISSION NOTICE
-Copyright (c) 1995-2006 International Business Machines Corporation and others
-
-All rights reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"),
-to deal in the Software without restriction, including without limitation
-the rights to use, copy, modify, merge, publish, distribute, and/or sell
-copies of the Software, and to permit persons
-to whom the Software is furnished to do so, provided that the above
-copyright notice(s) and this permission notice appear in all copies
-of the Software and that both the above copyright notice(s) and this
-permission notice appear in supporting documentation.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL
-THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM,
-OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
-RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
-USE OR PERFORMANCE OF THIS SOFTWARE.
-
-Except as contained in this notice, the name of a copyright holder shall not be
-used in advertising or otherwise to promote the sale, use or other dealings in
-this Software without prior written authorization of the copyright holder.
-
-All trademarks and registered trademarks mentioned herein are the property of their respective owners.
-
- * Smallest Collator strength value. When all other strengths are equal,
- * the IDENTICAL strength is used as a tiebreaker. The Unicode code point
- * values of the NFD form of each string are compared, just in case there
- * is no difference.
- * See class documentation for more explanation.
- *
- * Note this value is different from JDK's
- * Decomposition mode value. With NO_DECOMPOSITION set, Strings
- * will not be decomposed for collation. This is the default
- * decomposition setting unless otherwise specified by the locale
- * used to create the Collator. Note this value is different from the JDK's. Decomposition mode value. With CANONICAL_DECOMPOSITION set,
- * characters that are canonical variants according to the Unicode standard
- * will be decomposed for collation. CANONICAL_DECOMPOSITION corresponds to Normalization Form D as
- * described in
- * Unicode Technical Report #15.
- * Example of use:
- *
- * E.g. with strength == SECONDARY, the tertiary difference is ignored
- *
- * E.g. with strength == PRIMARY, the secondary and tertiary difference
- * are ignored.
- * Example of use:
- * Example of use:
- *
-* The collation table is composed of a list of collation rules, where each
-* rule is of three forms:
-*
-* '@' : Indicates that accents are sorted backwards, as in French.
-* '&' : Indicates that the next rule follows the position to where
-* the reset text-argument would be sorted.
-*
-* This sounds more complicated than it is in practice. For example, the
-* following are equivalent ways of expressing the same thing:
-*
-* Ignorable Characters
-*
-* For ignorable characters, the first rule must start with a relation (the
-* examples we have used above are really fragments; "a < b" really should be
-* "< a < b"). If, however, the first relation is not "<", then all the all
-* text-arguments up to the first "<" are ignorable. For example, ", - < a < b"
-* makes "-" an ignorable character, as we saw earlier in the word
-* "black-birds". In the samples for different languages, you see that most
-* accents are ignorable.
-*
-* Normalization and Accents
-*
-*
-* This allows you to use a RuleBasedCollator to compare accented strings even
-* when the collator is set to NO_DECOMPOSITION. However, if the strings to be
-* collated contain combining sequences that may not be in canonical order, you
-* should set the collator to CANONICAL_DECOMPOSITION to enable sorting of
-* combining sequences.
-* For more information, see
-* The Unicode Standard, Version 3.0.)
-*
-* Errors
-*
-* The following are errors:
-* Examples
-* Simple: "< a < b < c < d"
-* Norwegian: "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J
-* < k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T
-* < u,U< v,V< w,W< x,X< y,Y< z,Z
-* < ?=a?,?=A?
-* ;aa,AA< ?,?< ?,?"
-*
-*
-* Normally, to create a rule-based Collator object, you will use
-*
-* Combining
-* Another more interesting example would be to make changes on an existing
-* table to create a new
-* The following example demonstrates how to change the order of
-* non-spacing accents,
-*
-* The last example shows how to put new primary ordering in before the
-* default setting. For example, in Japanese
-* @author syn wee quek
-* @stable ICU 2.4
-*/
-public final class RuleBasedCollator extends Collator {
- private int m_collator_;
- private int m_hashcode_ = 0;
-
- /**
- * RuleBasedCollator constructor. This takes the table rules and builds a
- * collation table out of them. Please see RuleBasedCollator class
- * description for more details on the collation rule syntax.
- * @param rules the collation rules to build the collation table from.
- * @exception ParseException thrown if rules are empty or a Runtime error
- * if collator can not be created.
- * @stable ICU 2.4
- */
- public RuleBasedCollator(String rules) throws ParseException {
- if (rules == null) {
- throw new NullPointerException();
- }
- m_collator_ = NativeCollation.openCollatorFromRules(rules,
- CollationAttribute.VALUE_OFF, CollationAttribute.VALUE_DEFAULT_STRENGTH);
- }
-
- /**
- * RuleBasedCollator constructor. This takes the table rules and builds a
- * collation table out of them. Please see RuleBasedCollator class
- * description for more details on the collation rule syntax.
- * @param rules the collation rules to build the collation table from.
- * @param strength collation strength
- * @exception ParseException thrown if rules are empty or a Runtime error
- * if collator can not be created.
- * @see #PRIMARY
- * @see #SECONDARY
- * @see #TERTIARY
- * @see #QUATERNARY
- * @see #IDENTICAL
- * @stable ICU 2.4
- */
- public RuleBasedCollator(String rules, int strength) throws ParseException {
- if (rules == null) {
- throw new NullPointerException();
- }
- m_collator_ = NativeCollation.openCollatorFromRules(rules, CollationAttribute.VALUE_OFF, strength);
- }
-
- /**
- * RuleBasedCollator constructor. This takes the table rules and builds a
- * collation table out of them. Please see RuleBasedCollator class
- * description for more details on the collation rule syntax.
- * Note API change starting from release 2.4. Prior to release 2.4, the
- * normalizationMode argument values are from the class
- * com.ibm.icu4jni.text.Normalization. In 2.4,
- * the valid normalizationMode arguments for this API are
- * CollationAttribute.VALUE_ON and CollationAttribute.VALUE_OFF.
- * Example of use:
- * Sets the decomposition mode of the Collator object on or off.
- * If the decomposition mode is set to on, string would be decomposed into
- * NFD format where necessary before sorting.
- *
- */
-public final class TextAttribute extends Attribute {
-
- /** The Constant serialVersionUID. */
- private static final long serialVersionUID = 7744112784117861702L;
-
- // set of available text attributes
- /** The Constant attrMap. */
- private static final Mapnull
to indicate an
- * unspecified set of the properties has changed.
- * @param oldValue
- * the previous value of the property, or null
if
- * the propertyName
is null
or the
- * previous value is unknown.
- * @param newValue
- * the new value of the property, or null
if the
- * propertyName
is null
or the new
- * value is unknown..
- * @param index
- * the index of the property.
- */
- public IndexedPropertyChangeEvent(Object source, String propertyName,
- Object oldValue, Object newValue, int index) {
- super(source, propertyName, oldValue, newValue);
- this.index = index;
- }
-
- /**
- * Answer the index of the property that was changed in this event.
- *
- * @return the property element index.
- */
- public int getIndex() {
- return index;
- }
-}
diff --git a/awt-kernel/src/main/java/java/beans/PropertyChangeEvent.java b/awt-kernel/src/main/java/java/beans/PropertyChangeEvent.java
deleted file mode 100644
index d614be3..0000000
--- a/awt-kernel/src/main/java/java/beans/PropertyChangeEvent.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.beans;
-
-import java.util.EventObject;
-
-/**
- * An event that indicates that a constraint or a boundary of a property has
- * changed.
- */
-public class PropertyChangeEvent extends EventObject {
-
- private static final long serialVersionUID = 7042693688939648123L;
-
- String propertyName;
-
- Object oldValue;
-
- Object newValue;
-
- Object propagationId;
-
- /**
- * The constructor used to create a new {@code PropertyChangeEvent}.
- *
- * @param source
- * the changed bean.
- * @param propertyName
- * the changed property, or null
to indicate an
- * unspecified set of the properties has changed.
- * @param oldValue
- * the previous value of the property, or null
if
- * the propertyName
is null
or the
- * previous value is unknown.
- * @param newValue
- * the new value of the property, or null
if the
- * propertyName
is null
or the new
- * value is unknown.
- */
- public PropertyChangeEvent(Object source, String propertyName,
- Object oldValue, Object newValue) {
- super(source);
-
- this.propertyName = propertyName;
- this.oldValue = oldValue;
- this.newValue = newValue;
- }
-
- /**
- * Returns the name of the property that has changed. If an unspecified set
- * of properties has changed it returns null.
- *
- * @return the name of the property that has changed, or null.
- */
- public String getPropertyName() {
- return propertyName;
- }
-
- /**
- * Sets the propagationId object.
- *
- * @see #getPropagationId()
- */
- public void setPropagationId(Object propagationId) {
- this.propagationId = propagationId;
- }
-
- /**
- * Returns the propagationId object. This is reserved for future use. Beans
- * 1.0 demands that a listener receiving this property and then sending its
- * own PropertyChangeEvent sets the received propagationId on the new
- * PropertyChangeEvent's propagationId field.
- *
- * @return the propagationId object.
- */
- public Object getPropagationId() {
- return propagationId;
- }
-
- /**
- * Returns the old value that the property had. If the old value is unknown
- * this method returns null.
- *
- * @return the old property value or null.
- */
- public Object getOldValue() {
- return oldValue;
- }
-
- /**
- * Returns the new value that the property now has. If the new value is
- * unknown this method returns null.
- *
- * @return the old property value or null.
- */
- public Object getNewValue() {
- return newValue;
- }
-}
diff --git a/awt-kernel/src/main/java/java/beans/PropertyChangeListener.java b/awt-kernel/src/main/java/java/beans/PropertyChangeListener.java
deleted file mode 100644
index a0a4201..0000000
--- a/awt-kernel/src/main/java/java/beans/PropertyChangeListener.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.beans;
-
-import java.util.EventListener;
-
-/**
- * A PropertyChangeListener can subscribe with a event source. Whenever that
- * source raises a PropertyChangeEvent this listener will get notified.
- */
-public interface PropertyChangeListener extends EventListener {
-
- /**
- * The source bean calls this method when an event is raised.
- *
- * @param event
- * the {@link PropertyChangeEvent} object which contains the name
- * and the old and new value of the property that has changed.
- */
- public void propertyChange(PropertyChangeEvent event);
-}
diff --git a/awt-kernel/src/main/java/java/beans/PropertyChangeListenerProxy.java b/awt-kernel/src/main/java/java/beans/PropertyChangeListenerProxy.java
deleted file mode 100644
index 4841b72..0000000
--- a/awt-kernel/src/main/java/java/beans/PropertyChangeListenerProxy.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.beans;
-
-import java.util.EventListenerProxy;
-
-/**
- * The implementation of this listener proxy just delegates the received events
- * to its listener.
- */
-public class PropertyChangeListenerProxy extends EventListenerProxy implements
- PropertyChangeListener {
-
- String propertyName;
-
- /**
- * Creates a new listener proxy that associates a listener with a property
- * name.
- *
- * @param propertyName
- * the name of the associated property.
- * @param listener
- * the listener to delegate incoming events to.
- */
- public PropertyChangeListenerProxy(String propertyName,
- PropertyChangeListener listener) {
- super(listener);
- this.propertyName = propertyName;
- }
-
- /**
- * Returns the name of the property associated with this listener proxy.
- *
- * @return the name of the associated property.
- */
- public String getPropertyName() {
- return propertyName;
- }
-
- public void propertyChange(PropertyChangeEvent event) {
- PropertyChangeListener listener = (PropertyChangeListener) getListener();
- listener.propertyChange(event);
- }
-}
diff --git a/awt-kernel/src/main/java/java/beans/PropertyChangeSupport.java b/awt-kernel/src/main/java/java/beans/PropertyChangeSupport.java
deleted file mode 100644
index 32e2da6..0000000
--- a/awt-kernel/src/main/java/java/beans/PropertyChangeSupport.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.beans;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This utility class
- *
- */
-public class PropertyChangeSupport implements Serializable {
-
- private static final long serialVersionUID = 6401253773779951803l;
-
- private transient Object sourceBean;
-
- private transient ListICU License - ICU 1.8.1 and later
-
-
-
- * while(i
- * String src = new String(mySource);
- * int i,codepoint;
- * boolean passed = false;
- * while(i
- *
- * @param codepoint Unicode code point as int value
- * @return true if a character can be converted
- * @obsolete ICU 2.4
- * @deprecated ICU 3.4
- */
- public boolean canEncode(int codepoint) {
- return NativeConverter.canEncode(converterHandle, codepoint);
- }
-
- /**
- * Releases the system resources by cleanly closing ICU converter opened
- * @exception Throwable exception thrown by super class' finalize method
- * @stable ICU 2.4
- */
- protected void finalize() throws Throwable {
- NativeConverter.closeConverter(converterHandle);
- super.finalize();
- converterHandle=0;
- }
-
- //------------------------------------------
- // private utility methods
- //------------------------------------------
- private final int getArray(ByteBuffer out) {
- if(out.hasArray()){
- // BEGIN android-changed: take arrayOffset into account
- output = out.array();
- outEnd = out.arrayOffset() + out.limit();
- return out.arrayOffset() + out.position();
- // END android-changed
- }else{
- outEnd = out.remaining();
- // BEGIN android-added
- if (allocatedOutput == null || (outEnd > allocatedOutput.length)) {
- allocatedOutput = new byte[outEnd];
- }
- output = allocatedOutput;
- // END android-added
- //since the new
- // buffer start position
- // is 0
- return 0;
- }
- }
-
- private final int getArray(CharBuffer in) {
- if(in.hasArray()){
- // BEGIN android-changed: take arrayOffset into account
- input = in.array();
- inEnd = in.arrayOffset() + in.limit();
- return in.arrayOffset() + in.position() + savedInputHeldLen;/*exclude the number fo bytes held in previous conversion*/
- // END android-changed
- }else{
- inEnd = in.remaining();
- // BEGIN android-added
- if (allocatedInput == null || (inEnd > allocatedInput.length)) {
- allocatedInput = new char[inEnd];
- }
- input = allocatedInput;
- // END android-added
- // save the current position
- int pos = in.position();
- in.get(input,0,inEnd);
- // reset the position
- in.position(pos);
- // the start position
- // of the new buffer
- // is whatever is savedInputLen
- return savedInputHeldLen;
- }
-
- }
- private final void setPosition(ByteBuffer out) {
-
- if (out.hasArray()) {
- // in getArray method we accessed the
- // array backing the buffer directly and wrote to
- // it, so just just set the position and return.
- // This is done to avoid the creation of temp array.
- // BEGIN android-changed: take arrayOffset into account
- out.position(out.position() + data[OUTPUT_OFFSET] - out.arrayOffset());
- // END android-changed
- } else {
- out.put(output, 0, data[OUTPUT_OFFSET]);
- }
- // BEGIN android-added
- // release reference to output array, which may not be ours
- output = null;
- // END android-added
- }
- private final void setPosition(CharBuffer in){
-
-// BEGIN android-removed
-// // was there input held in the previous invocation of encodeLoop
-// // that resulted in output in this invocation?
-// if(data[OUTPUT_OFFSET]>0 && savedInputHeldLen>0){
-// int len = in.position() + data[INPUT_OFFSET] + savedInputHeldLen;
-// in.position(len);
-// savedInputHeldLen = data[INPUT_HELD];
-// }else{
-// in.position(in.position() + data[INPUT_OFFSET] + savedInputHeldLen);
-// savedInputHeldLen = data[INPUT_HELD];
-// in.position(in.position() - savedInputHeldLen);
-// }
-// END android-removed
-
-// BEGIN android-added
- // Slightly rewired original code to make it cleaner. Also
- // added a fix for the problem where input charatcers got
- // lost when invalid characters were encountered. Not sure
- // what happens when data[INVALID_CHARS] is > 1, though,
- // since we never saw that happening.
- int len = in.position() + data[INPUT_OFFSET] + savedInputHeldLen;
- len -= data[INVALID_CHARS]; // Otherwise position becomes wrong.
- in.position(len);
- savedInputHeldLen = data[INPUT_HELD];
- // was there input held in the previous invocation of encodeLoop
- // that resulted in output in this invocation?
- if(!(data[OUTPUT_OFFSET]>0 && savedInputHeldLen>0)){
- in.position(in.position() - savedInputHeldLen);
- }
-// END android-added
-
- // BEGIN android-added
- // release reference to input array, which may not be ours
- input = null;
- // END android-added
- }
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java b/icu/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java
deleted file mode 100644
index fe0f920..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/charset/CharsetICU.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.charset;
-
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.util.HashMap;
-import java.util.Map;
-
-public final class CharsetICU extends Charset {
- private final String icuCanonicalName;
- /**
- * Constructor to create a the CharsetICU object
- * @param canonicalName the canonical name as a string
- * @param aliases the alias set as an array of strings
- * @stable ICU 2.4
- */
- protected CharsetICU(String canonicalName, String icuCanonName, String[] aliases) {
- super(canonicalName, aliases);
- icuCanonicalName = icuCanonName;
- }
- /**
- * Returns a new decoder instance of this charset object
- * @return a new decoder object
- * @stable ICU 2.4
- */
- public CharsetDecoder newDecoder() {
- long converterHandle = NativeConverter.openConverter(icuCanonicalName);
- return new CharsetDecoderICU(this, converterHandle);
- }
-
- // hardCoded list of replacement bytes
- private static final Map
-* RuleBasedCollator coll = Collator.getInstance();
-* CollationElementIterator iterator = coll.getCollationElementIterator("abc");
-* int ce = 0;
-* while (ce != CollationElementIterator.NULLORDER) {
-* ce = iterator.next();
-* }
-* iterator.reset();
-* while (ce != CollationElementIterator.NULLORDER) {
-* ce = iterator.previous();
-* }
-*
-* @author syn wee quek
-* @stable ICU 2.4
-*/
-
-public final class CollationElementIterator
-{
- // public data member -------------------------------------------
-
- /**
- * @stable ICU 2.4
- */
- public static final int NULLORDER = 0xFFFFFFFF;
-
- // public methods -----------------------------------------------
-
- /**
- * Reset the collation elements to their initial state.
- * This will move the 'cursor' to the beginning of the text.
- * @stable ICU 2.4
- */
- public void reset()
- {
- NativeCollation.reset(m_collelemiterator_);
- }
-
- /**
- * Get the ordering priority of the next collation element in the text.
- * A single character may contain more than one collation element.
- * @return next collation elements ordering, or NULLORDER if the end of the
- * text is reached.
- * @stable ICU 2.4
- */
- public int next()
- {
- return NativeCollation.next(m_collelemiterator_);
- }
-
- /**
- * Get the ordering priority of the previous collation element in the text.
- * A single character may contain more than one collation element.
- * @return previous collation element ordering, or NULLORDER if the end of
- * the text is reached.
- * @stable ICU 2.4
- */
- public int previous()
- {
- return NativeCollation.previous(m_collelemiterator_);
- }
-
- /**
- * Get the maximum length of any expansion sequences that end with the
- * specified comparison order.
- * @param order collation order returned by previous or next.
- * @return maximum size of the expansion sequences ending with the collation
- * element or 1 if collation element does not occur at the end of
- * any expansion sequence
- * @stable ICU 2.4
- */
- public int getMaxExpansion(int order)
- {
- return NativeCollation.getMaxExpansion(m_collelemiterator_, order);
- }
-
- /**
- * Set the text containing the collation elements.
- * @param source text containing the collation elements.
- * @stable ICU 2.4
- */
- public void setText(String source)
- {
- NativeCollation.setText(m_collelemiterator_, source);
- }
-
- // BEGIN android-added
- public void setText(CharacterIterator source)
- {
- NativeCollation.setText(m_collelemiterator_, source.toString());
- }
- // END android-added
-
- /**
- * Get the offset of the current source character.
- * This is an offset into the text of the character containing the current
- * collation elements.
- * @return offset of the current source character.
- * @stable ICU 2.4
- */
- public int getOffset()
- {
- return NativeCollation.getOffset(m_collelemiterator_);
- }
-
- /**
- * Set the offset of the current source character.
- * This is an offset into the text of the character to be processed.
- * @param offset The desired character offset.
- * @stable ICU 2.4
- */
- public void setOffset(int offset)
- {
- NativeCollation.setOffset(m_collelemiterator_, offset);
- }
-
- /**
- * Gets the primary order of a collation order.
- * @param order the collation order
- * @return the primary order of a collation order.
- * @stable ICU 2.4
- */
- public static int primaryOrder(int order)
- {
- return ((order & PRIMARY_ORDER_MASK_) >> PRIMARY_ORDER_SHIFT_) &
- UNSIGNED_16_BIT_MASK_;
- }
-
- /**
- * Gets the secondary order of a collation order.
- * @param order the collation order
- * @return the secondary order of a collation order.
- * @stable ICU 2.4
- */
- public static int secondaryOrder(int order)
- {
- return (order & SECONDARY_ORDER_MASK_) >> SECONDARY_ORDER_SHIFT_;
- }
-
- /**
- * Gets the tertiary order of a collation order.
- * @param order the collation order
- * @return the tertiary order of a collation order.
- * @stable ICU 2.4
- */
- public static int tertiaryOrder(int order)
- {
- return order & TERTIARY_ORDER_MASK_;
- }
-
- // protected constructor ----------------------------------------
-
- /**
- * CollationElementIteratorJNI constructor.
- * The only caller of this class should be
- * RuleBasedCollator.getCollationElementIterator().
- * @param collelemiteratoraddress address of C collationelementiterator
- */
- CollationElementIterator(int collelemiteratoraddress)
- {
- m_collelemiterator_ = collelemiteratoraddress;
- }
-
- // protected methods --------------------------------------------
-
- /**
- * Garbage collection.
- * Close C collator and reclaim memory.
- * @stable ICU 2.4
- */
- protected void finalize()
- {
- NativeCollation.closeElements(m_collelemiterator_);
- }
-
- // private data members -----------------------------------------
-
- /**
- * C collator
- */
- private int m_collelemiterator_;
-
- /**
- * ICU constant primary order mask for collation elements
- */
- private static final int PRIMARY_ORDER_MASK_ = 0xffff0000;
- /**
- * ICU constant secondary order mask for collation elements
- */
- private static final int SECONDARY_ORDER_MASK_ = 0x0000ff00;
- /**
- * ICU constant tertiary order mask for collation elements
- */
- private static final int TERTIARY_ORDER_MASK_ = 0x000000ff;
- /**
- * ICU constant primary order shift for collation elements
- */
- private static final int PRIMARY_ORDER_SHIFT_ = 16;
- /**
- * ICU constant secondary order shift for collation elements
- */
- private static final int SECONDARY_ORDER_SHIFT_ = 8;
- /**
- * Unsigned 16 bit mask
- */
- private static final int UNSIGNED_16_BIT_MASK_ = 0x0000FFFF;
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/CollationKey.java b/icu/src/main/java/com/ibm/icu4jni/text/CollationKey.java
deleted file mode 100644
index dbd714c..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/CollationKey.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-/**
- * A concrete implementation of the abstract java.text.CollationKey.
- */
-public final class CollationKey extends java.text.CollationKey {
- /**
- * The key.
- */
- private final byte[] bytes;
-
- /**
- * Cached hash value.
- */
- private int hashCode;
-
- CollationKey(String source, byte[] bytes) {
- super(source);
- this.bytes = bytes;
- }
-
- public int compareTo(java.text.CollationKey other) {
- // Get the bytes from the other collation key.
- final byte[] rhsBytes;
- if (other instanceof CollationKey) {
- rhsBytes = ((CollationKey) other).bytes;
- } else {
- rhsBytes = other.toByteArray();
- }
-
- if (bytes == null || bytes.length == 0) {
- if (rhsBytes == null || rhsBytes.length == 0) {
- return 0;
- }
- return -1;
- } else {
- if (rhsBytes == null || rhsBytes.length == 0) {
- return 1;
- }
- }
-
- int count = Math.min(bytes.length, rhsBytes.length);
- for (int i = 0; i < count; ++i) {
- int s = bytes[i] & 0xff;
- int t = rhsBytes[i] & 0xff;
- if (s < t) {
- return -1;
- }
- if (s > t) {
- return 1;
- }
- }
- if (bytes.length < rhsBytes.length) {
- return -1;
- }
- if (bytes.length > rhsBytes.length) {
- return 1;
- }
- return 0;
- }
-
- /**
- * Checks if target object is equal to this object.
- * Target is first casted to CollationKey and bitwise compared.
- * @param target comparison object
- * @return true if both objects are equal, false otherwise
- * @stable ICU 2.4
- */
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
- if (!(object instanceof CollationKey)) {
- return false;
- }
- return compareTo((CollationKey) object) == 0;
- }
-
- /**
- * Creates a hash code for this CollationKey.
- * Compute the hash by iterating sparsely over about 32 (up to 63) bytes
- * spaced evenly through the string. For each byte, multiply the previous
- * hash value by a prime number and add the new byte in, like a linear
- * congruential random number generator, producing a pseudo-random
- * deterministic value well distributed over the output range.
- * @return hash value of collation key. Hash value is never 0.
- * @stable ICU 2.4
- */
- public int hashCode() {
- if (hashCode == 0) {
- if (bytes != null && bytes.length != 0) {
- int len = bytes.length;
- int inc = ((len - 32) / 32) + 1;
- for (int i = 0; i < len;) {
- hashCode = (hashCode * 37) + bytes[i];
- i += inc;
- }
- }
- if (hashCode == 0) {
- hashCode = 1;
- }
- }
- return hashCode;
- }
-
- public byte[] toByteArray() {
- if (bytes == null || bytes.length == 0) {
- return null;
- }
- return bytes.clone();
- }
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/Collator.java b/icu/src/main/java/com/ibm/icu4jni/text/Collator.java
deleted file mode 100644
index 9eb85ea..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/Collator.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-import com.ibm.icu4jni.text.RuleBasedCollator;
-import java.util.Locale;
-
-public abstract class Collator implements Cloneable {
- /**
- * Strongest collator strength value. Typically used to denote differences
- * between base characters. See class documentation for more explanation.
- * @see #setStrength
- * @see #getStrength
- * @stable ICU 2.4
- */
- public final static int PRIMARY = CollationAttribute.VALUE_PRIMARY;
-
- /**
- * Second level collator strength value.
- * Accents in the characters are considered secondary differences.
- * Other differences between letters can also be considered secondary
- * differences, depending on the language.
- * See class documentation for more explanation.
- * @see #setStrength
- * @see #getStrength
- * @stable ICU 2.4
- */
- public final static int SECONDARY = CollationAttribute.VALUE_SECONDARY;
-
- /**
- * Third level collator strength value.
- * Upper and lower case differences in characters are distinguished at this
- * strength level. In addition, a variant of a letter differs from the base
- * form on the tertiary level.
- * See class documentation for more explanation.
- * @see #setStrength
- * @see #getStrength
- * @stable ICU 2.4
- */
- public final static int TERTIARY = CollationAttribute.VALUE_TERTIARY;
-
- /**
- * Fourth level collator strength value.
- * When punctuation is ignored
- *
- * (see Ignoring Punctuations in the user guide) at PRIMARY to TERTIARY
- * strength, an additional strength level can
- * be used to distinguish words with and without punctuation.
- * See class documentation for more explanation.
- * @see #setStrength
- * @see #getStrength
- * @stable ICU 2.4
- */
- public final static int QUATERNARY = CollationAttribute.VALUE_QUATERNARY;
-
- /**
- *
- * . Collator myCollation = Collator.getInstance(Locale::US);
- * . myCollation.setStrength(CollationAttribute.VALUE_PRIMARY);
- * . // result would be CollationAttribute.VALUE_EQUAL
- * . // ("abc" == "ABC")
- * . // (no primary difference between "abc" and "ABC")
- * . int result = myCollation.compare("abc", "ABC",3);
- * . myCollation.setStrength(CollationAttribute.VALUE_TERTIARY);
- * . // result would be Collation.LESS (abc" <<< "ABC")
- * . // (with tertiary difference between "abc" and "ABC")
- * . int result = myCollation.compare("abc", "ABC",3);
- *
- * @stable ICU 2.4
- */
- public abstract int compare(String source, String target);
-
- /**
- * Get the decomposition mode of this Collator.
- * @return the decomposition mode
- * @see #CANONICAL_DECOMPOSITION
- * @see #NO_DECOMPOSITION
- * @stable ICU 2.4
- */
- public abstract int getDecomposition();
-
- /**
- * Set the normalization mode used int this object
- * The normalization mode influences how strings are compared.
- * @param mode desired normalization mode
- * @see #CANONICAL_DECOMPOSITION
- * @see #NO_DECOMPOSITION
- * @stable ICU 2.4
- */
- public abstract void setDecomposition(int mode);
-
- /**
- * Determines the minimum strength that will be use in comparison or
- * transformation.
- *
- * . Collator myCollation = Collator.createInstance(Locale::US);
- * . myCollation.setStrength(PRIMARY);
- * . // result will be "abc" == "ABC"
- * . // tertiary differences will be ignored
- * . int result = myCollation->compare("abc", "ABC");
- *
- * @param strength the new comparison level.
- * @see #PRIMARY
- * @see #SECONDARY
- * @see #TERTIARY
- * @see #QUATERNARY
- * @see #IDENTICAL
- * @stable ICU 2.4
- */
- public abstract void setStrength(int strength);
-
- /**
- * Sets the attribute to be used in comparison or transformation.
- *
- * . Collator myCollation = Collator.createInstance(Locale::US);
- * . myCollation.setAttribute(CollationAttribute.CASE_LEVEL,
- * . CollationAttribute.VALUE_ON);
- * . int result = myCollation->compare("\\u30C3\\u30CF",
- * . "\\u30C4\\u30CF");
- * . // result will be -1.
- *
- * @param type the attribute to be set from CollationAttribute
- * @param value attribute value from CollationAttribute
- * @stable ICU 2.4
- */
- public abstract void setAttribute(int type, int value);
-
- /**
- * Get the sort key as an CollationKey object from the argument string.
- * To retrieve sort key in terms of byte arrays, use the method as below
- *
- * Collator collator = Collator.getInstance();
- * CollationKey collationKey = collator.getCollationKey("string");
- * byte[] array = collationKey.toByteArray();
- *
- * Byte array result are zero-terminated and can be compared using
- * java.util.Arrays.equals();
- * @param source string to be processed.
- * @return the sort key
- * @stable ICU 2.4
- */
- public abstract CollationKey getCollationKey(String source);
-
- /**
- * Returns a hash of this collation object
- * @return hash of this collation object
- * @stable ICU 2.4
- */
- public abstract int hashCode();
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java b/icu/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java
deleted file mode 100644
index 272d525..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/NativeBreakIterator.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.text;
-
-import java.text.CharacterIterator;
-import java.text.StringCharacterIterator;
-import java.util.Locale;
-
-public final class NativeBreakIterator implements Cloneable {
- // Acceptable values for the 'type' field.
- private static final int BI_CHAR_INSTANCE = 1;
- private static final int BI_WORD_INSTANCE = 2;
- private static final int BI_LINE_INSTANCE = 3;
- private static final int BI_SENT_INSTANCE = 4;
-
- private final int addr;
- private final int type;
- private CharacterIterator charIter;
-
- private NativeBreakIterator(int iterAddr, int type) {
- this.addr = iterAddr;
- this.type = type;
- this.charIter = new StringCharacterIterator("");
- }
-
- @Override
- public Object clone() {
- int cloneAddr = cloneImpl(this.addr);
- NativeBreakIterator clone = new NativeBreakIterator(cloneAddr, this.type);
- // The RI doesn't clone the CharacterIterator.
- clone.charIter = this.charIter;
- return clone;
- }
-
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
- if (!(object instanceof NativeBreakIterator)) {
- return false;
- }
- // TODO: is this sufficient? shouldn't we be checking the underlying rules?
- NativeBreakIterator rhs = (NativeBreakIterator) object;
- return type == rhs.type && charIter.equals(rhs.charIter);
- }
-
- @Override
- public int hashCode() {
- return 42; // No-one uses BreakIterator as a hash key.
- }
-
- @Override
- protected void finalize() {
- closeBreakIteratorImpl(this.addr);
- }
-
- public int current() {
- return currentImpl(this.addr);
- }
-
- public int first() {
- return firstImpl(this.addr);
- }
-
- public int following(int offset) {
- return followingImpl(this.addr, offset);
- }
-
- public CharacterIterator getText() {
- int newLoc = currentImpl(this.addr);
- this.charIter.setIndex(newLoc);
- return this.charIter;
- }
-
- public int last() {
- return lastImpl(this.addr);
- }
-
- public int next(int n) {
- return nextImpl(this.addr, n);
- }
-
- public int next() {
- return nextImpl(this.addr, 1);
- }
-
- public int previous() {
- return previousImpl(this.addr);
- }
-
- public void setText(CharacterIterator newText) {
- this.charIter = newText;
- StringBuilder sb = new StringBuilder();
- for (char c = newText.first(); c != CharacterIterator.DONE; c = newText.next()) {
- sb.append(c);
- }
- setTextImpl(this.addr, sb.toString());
- }
-
- public void setText(String newText) {
- setText(new StringCharacterIterator(newText));
- }
-
- public boolean isBoundary(int offset) {
- return isBoundaryImpl(this.addr, offset);
- }
-
- public int preceding(int offset) {
- return precedingImpl(this.addr, offset);
- }
-
- public static NativeBreakIterator getCharacterInstance(Locale where) {
- return new NativeBreakIterator(getCharacterInstanceImpl(where.toString()), BI_CHAR_INSTANCE);
- }
-
- public static NativeBreakIterator getLineInstance(Locale where) {
- return new NativeBreakIterator(getLineInstanceImpl(where.toString()), BI_LINE_INSTANCE);
- }
-
- public static NativeBreakIterator getSentenceInstance(Locale where) {
- return new NativeBreakIterator(getSentenceInstanceImpl(where.toString()), BI_SENT_INSTANCE);
- }
-
- public static NativeBreakIterator getWordInstance(Locale where) {
- return new NativeBreakIterator(getWordInstanceImpl(where.toString()), BI_WORD_INSTANCE);
- }
-
- private static native int getCharacterInstanceImpl(String locale);
- private static native int getWordInstanceImpl(String locale);
- private static native int getLineInstanceImpl(String locale);
- private static native int getSentenceInstanceImpl(String locale);
- private static native void closeBreakIteratorImpl(int addr);
- private static native void setTextImpl(int addr, String text);
- private static native int cloneImpl(int addr);
- private static native int precedingImpl(int addr, int offset);
- private static native boolean isBoundaryImpl(int addr, int offset);
- private static native int nextImpl(int addr, int n);
- private static native int previousImpl(int addr);
- private static native int currentImpl(int addr);
- private static native int firstImpl(int addr);
- private static native int followingImpl(int addr, int offset);
- private static native int lastImpl(int addr);
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/NativeCollation.java b/icu/src/main/java/com/ibm/icu4jni/text/NativeCollation.java
deleted file mode 100644
index d481790..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/NativeCollation.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-/**
-* Package static class for declaring all native methods for collation use.
-* @author syn wee quek
-* @internal ICU 2.4
-*/
-
-final class NativeCollation
-{
- // collator methods ---------------------------------------------
-
- public NativeCollation() {
-
- }
-
- /**
- * Method to create a new C Collator using the argument locale rules.
- * @param locale locale name
- * @return new c collator
- * @internal ICU 2.4
- */
- static native int openCollator(String locale);
-
- /**
- * Method to create a new C Collator using the argument rules.
- * @param rules , set of collation rules
- * @param normalizationmode default normalization mode
- * @param collationstrength default collation strength
- * @return new c collator
- * @internal ICU 2.4
- */
- static native int openCollatorFromRules(String rules,
- int normalizationmode,
- int collationstrength);
-
- /**
- * Close a C collator
- * Once closed, a UCollatorOld should not be used.
- * @param collatoraddress The UCollatorOld to close
- * @internal ICU 2.4
- */
- static native void closeCollator(int collatoraddress);
-
- /**
- * Compare two strings.
- * The strings will be compared using the normalization mode and options
- * specified in openCollator or openCollatorFromRules
- * @param collatoraddress address of the c collator
- * @param source The source string.
- * @param target The target string.
- * @return result of the comparison, Collation.EQUAL,
- * Collation.GREATER or Collation.LESS
- * @internal ICU 2.4
- */
- static native int compare(int collatoraddress, String source,
- String target);
-
- /**
- * Get the normalization mode for this object.
- * The normalization mode influences how strings are compared.
- * @param collatoraddress
- * @return normalization mode; one of the values from Normalization
- * @internal ICU 2.4
- */
- static native int getNormalization(int collatoraddress);
-
- /**
- * Set the normalization mode used int this object
- * The normalization mode influences how strings are compared.
- * @param collatoraddress the address of the C collator
- * @param normalizationmode desired normalization mode; one of the values
- * from Normalization
- * @internal ICU 2.4
- */
- static native void setNormalization(int collatoraddress,
- int normalizationmode);
-
- /**
- * Get the collation rules from a UCollator.
- * The rules will follow the rule syntax.
- * @param collatoraddress the address of the C collator
- * @return collation rules.
- * @internal ICU 2.4
- */
- static native String getRules(int collatoraddress);
-
- /**
- * Get a sort key for the argument string
- * Sort keys may be compared using java.util.Arrays.equals
- * @param collatoraddress address of the C collator
- * @param source string for key to be generated
- * @return sort key
- * @internal ICU 2.4
- */
- static native byte[] getSortKey(int collatoraddress, String source);
-
- /**
- * Gets the version information for collation.
- * @param collatoraddress address of the C collator
- * @return version information
- * @internal ICU 2.4
- */
- // private native String getVersion(int collatoraddress);
-
- /**
- * Universal attribute setter.
- * @param collatoraddress address of the C collator
- * @param type type of attribute to be set
- * @param value attribute value
- * @exception RuntimeException when error occurs while setting attribute value
- * @internal ICU 2.4
- */
- static native void setAttribute(int collatoraddress, int type, int value);
-
- /**
- * Universal attribute getter
- * @param collatoraddress address of the C collator
- * @param type type of attribute to be set
- * @return attribute value
- * @exception RuntimeException thrown when error occurs while getting attribute value
- * @internal ICU 2.4
- */
- static native int getAttribute(int collatoraddress, int type);
-
- /**
- * Thread safe cloning operation
- * @param collatoraddress address of C collator to be cloned
- * @return address of the new clone
- * @exception RuntimeException thrown when error occurs while cloning
- * @internal ICU 2.4
- */
- static native int safeClone(int collatoraddress);
-
- /**
- * Create a CollationElementIterator object that will iterator over the
- * elements in a string, using the collation rules defined in this
- * RuleBasedCollator
- * @param collatoraddress address of C collator
- * @param source string to iterate over
- * @return address of C collationelementiterator
- * @internal ICU 2.4
- */
- static native int getCollationElementIterator(int collatoraddress,
- String source);
-
-
- // collationelementiterator methods -------------------------------------
-
- /**
- * Close a C collation element iterator.
- * @param address of C collation element iterator to close.
- * @internal ICU 2.4
- */
- static native void closeElements(int address);
-
- /**
- * Reset the collation elements to their initial state.
- * This will move the 'cursor' to the beginning of the text.
- * @param address of C collation element iterator to reset.
- * @internal ICU 2.4
- */
- static native void reset(int address);
-
- /**
- * Get the ordering priority of the next collation element in the text.
- * A single character may contain more than one collation element.
- * @param address if C collation elements containing the text.
- * @return next collation elements ordering, or NULLORDER if the end of the
- * text is reached.
- * @internal ICU 2.4
- */
- static native int next(int address);
-
- /**
- * Get the ordering priority of the previous collation element in the text.
- * A single character may contain more than one collation element.
- * @param address of the C collation element iterator containing the text.
- * @return previous collation element ordering, or NULLORDER if the end of
- * the text is reached.
- * @internal ICU 2.4
- */
- static native int previous(int address);
-
- /**
- * Get the maximum length of any expansion sequences that end with the
- * specified comparison order.
- * @param address of the C collation element iterator containing the text.
- * @param order collation order returned by previous or next.
- * @return maximum length of any expansion sequences ending with the
- * specified order.
- * @internal ICU 2.4
- */
- static native int getMaxExpansion(int address, int order);
-
- /**
- * Set the text containing the collation elements.
- * @param address of the C collation element iterator to be set
- * @param source text containing the collation elements.
- * @internal ICU 2.4
- */
- static native void setText(int address, String source);
-
- /**
- * Get the offset of the current source character.
- * This is an offset into the text of the character containing the current
- * collation elements.
- * @param address of the C collation elements iterator to query.
- * @return offset of the current source character.
- * @internal ICU 2.4
- */
- static native int getOffset(int address);
-
- /**
- * Set the offset of the current source character.
- * This is an offset into the text of the character to be processed.
- * @param address of the C collation element iterator to set.
- * @param offset The desired character offset.
- * @internal ICU 2.4
- */
- static native void setOffset(int address, int offset);
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java b/icu/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java
deleted file mode 100644
index 6f751d5..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/NativeDecimalFormat.java
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.text;
-
-import com.ibm.icu4jni.util.LocaleData;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.math.RoundingMode;
-import java.text.AttributedCharacterIterator;
-import java.text.AttributedString;
-import java.text.DecimalFormatSymbols;
-import java.text.FieldPosition;
-import java.text.Format;
-import java.text.NumberFormat;
-import java.text.ParsePosition;
-import java.util.Currency;
-import java.util.Locale;
-
-public final class NativeDecimalFormat {
- /**
- * Constants corresponding to the native type UNumberFormatSymbol, for setSymbol.
- */
- private static final int UNUM_DECIMAL_SEPARATOR_SYMBOL = 0;
- private static final int UNUM_GROUPING_SEPARATOR_SYMBOL = 1;
- private static final int UNUM_PATTERN_SEPARATOR_SYMBOL = 2;
- private static final int UNUM_PERCENT_SYMBOL = 3;
- private static final int UNUM_ZERO_DIGIT_SYMBOL = 4;
- private static final int UNUM_DIGIT_SYMBOL = 5;
- private static final int UNUM_MINUS_SIGN_SYMBOL = 6;
- private static final int UNUM_PLUS_SIGN_SYMBOL = 7;
- private static final int UNUM_CURRENCY_SYMBOL = 8;
- private static final int UNUM_INTL_CURRENCY_SYMBOL = 9;
- private static final int UNUM_MONETARY_SEPARATOR_SYMBOL = 10;
- private static final int UNUM_EXPONENTIAL_SYMBOL = 11;
- private static final int UNUM_PERMILL_SYMBOL = 12;
- private static final int UNUM_PAD_ESCAPE_SYMBOL = 13;
- private static final int UNUM_INFINITY_SYMBOL = 14;
- private static final int UNUM_NAN_SYMBOL = 15;
- private static final int UNUM_SIGNIFICANT_DIGIT_SYMBOL = 16;
- private static final int UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL = 17;
- private static final int UNUM_FORMAT_SYMBOL_COUNT = 18;
-
- /**
- * Constants corresponding to the native type UNumberFormatAttribute, for
- * getAttribute/setAttribute.
- */
- private static final int UNUM_PARSE_INT_ONLY = 0;
- private static final int UNUM_GROUPING_USED = 1;
- private static final int UNUM_DECIMAL_ALWAYS_SHOWN = 2;
- private static final int UNUM_MAX_INTEGER_DIGITS = 3;
- private static final int UNUM_MIN_INTEGER_DIGITS = 4;
- private static final int UNUM_INTEGER_DIGITS = 5;
- private static final int UNUM_MAX_FRACTION_DIGITS = 6;
- private static final int UNUM_MIN_FRACTION_DIGITS = 7;
- private static final int UNUM_FRACTION_DIGITS = 8;
- private static final int UNUM_MULTIPLIER = 9;
- private static final int UNUM_GROUPING_SIZE = 10;
- private static final int UNUM_ROUNDING_MODE = 11;
- private static final int UNUM_ROUNDING_INCREMENT = 12;
- private static final int UNUM_FORMAT_WIDTH = 13;
- private static final int UNUM_PADDING_POSITION = 14;
- private static final int UNUM_SECONDARY_GROUPING_SIZE = 15;
- private static final int UNUM_SIGNIFICANT_DIGITS_USED = 16;
- private static final int UNUM_MIN_SIGNIFICANT_DIGITS = 17;
- private static final int UNUM_MAX_SIGNIFICANT_DIGITS = 18;
- private static final int UNUM_LENIENT_PARSE = 19;
-
- /**
- * Constants corresponding to the native type UNumberFormatTextAttribute, for
- * getTextAttribute/setTextAttribute.
- */
- private static final int UNUM_POSITIVE_PREFIX = 0;
- private static final int UNUM_POSITIVE_SUFFIX = 1;
- private static final int UNUM_NEGATIVE_PREFIX = 2;
- private static final int UNUM_NEGATIVE_SUFFIX = 3;
- private static final int UNUM_PADDING_CHARACTER = 4;
- private static final int UNUM_CURRENCY_CODE = 5;
- private static final int UNUM_DEFAULT_RULESET = 6;
- private static final int UNUM_PUBLIC_RULESETS = 7;
-
- /**
- * The address of the ICU DecimalFormat* on the native heap.
- */
- private final int addr;
-
- /**
- * The last pattern we gave to ICU, so we can make repeated applications cheap.
- * This helps in cases like String.format("%.2f,%.2f\n", x, y) where the DecimalFormat is
- * reused.
- */
- private String lastPattern;
-
- // TODO: store all these in DecimalFormat instead!
- private boolean negPrefNull;
- private boolean negSuffNull;
- private boolean posPrefNull;
- private boolean posSuffNull;
-
- /**
- * Cache the BigDecimal form of the multiplier. This is null until we've
- * formatted a BigDecimal (with a multiplier that is not 1), or the user has
- * explicitly called {@link #setMultiplier(int)} with any multiplier.
- */
- private BigDecimal multiplierBigDecimal = null;
-
- public NativeDecimalFormat(String pattern, DecimalFormatSymbols dfs) {
- try {
- this.addr = openDecimalFormatImpl(pattern, dfs.getCurrencySymbol(),
- dfs.getDecimalSeparator(), dfs.getDigit(), dfs.getGroupingSeparator(),
- dfs.getInfinity(), dfs.getInternationalCurrencySymbol(), dfs.getMinusSign(),
- dfs.getMonetaryDecimalSeparator(), dfs.getNaN(), dfs.getPatternSeparator(),
- dfs.getPercent(), dfs.getPerMill(), dfs.getZeroDigit());
- this.lastPattern = pattern;
- } catch (NullPointerException npe) {
- throw npe;
- } catch (RuntimeException re) {
- throw new IllegalArgumentException("syntax error: " + re.getMessage() + ": " + pattern);
- }
- }
-
- // Used to implement clone.
- private NativeDecimalFormat(NativeDecimalFormat other) {
- this.addr = cloneDecimalFormatImpl(other.addr);
- this.lastPattern = other.lastPattern;
- this.negPrefNull = other.negPrefNull;
- this.negSuffNull = other.negSuffNull;
- this.posPrefNull = other.posPrefNull;
- this.posSuffNull = other.posSuffNull;
- }
-
- // TODO: remove this and just have DecimalFormat.hashCode do the right thing itself.
- @Override
- public int hashCode() {
- return this.getPositivePrefix().hashCode();
- }
-
- @Override
- public Object clone() {
- return new NativeDecimalFormat(this);
- }
-
- @Override
- protected void finalize() {
- closeDecimalFormatImpl(this.addr);
- }
-
- /**
- * Note: this doesn't check that the underlying native DecimalFormat objects' configured
- * native DecimalFormatSymbols objects are equal. It is assumed that the
- * caller (DecimalFormat) will check the DecimalFormatSymbols objects
- * instead, for performance.
- *
- * This is also unreasonably expensive, calling down to JNI multiple times.
- *
- * TODO: remove this and just have DecimalFormat.equals do the right thing itself.
- */
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
- if (!(object instanceof NativeDecimalFormat)) {
- return false;
- }
- NativeDecimalFormat obj = (NativeDecimalFormat) object;
- if (obj.addr == this.addr) {
- return true;
- }
- return obj.toPattern().equals(this.toPattern()) &&
- obj.isDecimalSeparatorAlwaysShown() == this.isDecimalSeparatorAlwaysShown() &&
- obj.getGroupingSize() == this.getGroupingSize() &&
- obj.getMultiplier() == this.getMultiplier() &&
- obj.getNegativePrefix().equals(this.getNegativePrefix()) &&
- obj.getNegativeSuffix().equals(this.getNegativeSuffix()) &&
- obj.getPositivePrefix().equals(this.getPositivePrefix()) &&
- obj.getPositiveSuffix().equals(this.getPositiveSuffix()) &&
- obj.getMaximumIntegerDigits() == this.getMaximumIntegerDigits() &&
- obj.getMaximumFractionDigits() == this.getMaximumFractionDigits() &&
- obj.getMinimumIntegerDigits() == this.getMinimumIntegerDigits() &&
- obj.getMinimumFractionDigits() == this.getMinimumFractionDigits() &&
- obj.isGroupingUsed() == this.isGroupingUsed();
- }
-
- /**
- * Copies the DecimalFormatSymbols settings into our native peer in bulk.
- */
- public void setDecimalFormatSymbols(final DecimalFormatSymbols dfs) {
- setDecimalFormatSymbols(this.addr, dfs.getCurrencySymbol(), dfs.getDecimalSeparator(),
- dfs.getDigit(), dfs.getGroupingSeparator(), dfs.getInfinity(),
- dfs.getInternationalCurrencySymbol(), dfs.getMinusSign(),
- dfs.getMonetaryDecimalSeparator(), dfs.getNaN(), dfs.getPatternSeparator(),
- dfs.getPercent(), dfs.getPerMill(), dfs.getZeroDigit());
- }
-
- private BigDecimal applyMultiplier(BigDecimal valBigDecimal) {
- if (multiplierBigDecimal == null) {
- multiplierBigDecimal = BigDecimal.valueOf(getMultiplier());
- }
- // Get new value by multiplying multiplier.
- return valBigDecimal.multiply(multiplierBigDecimal);
- }
-
- public StringBuffer formatBigDecimal(BigDecimal value, StringBuffer buffer, FieldPosition field) {
- if (buffer == null || field == null) {
- throw new NullPointerException();
- }
- if (getMultiplier() != 1) {
- value = applyMultiplier(value);
- }
- StringBuilder val = new StringBuilder();
- val.append(value.unscaledValue().toString(10));
- int scale = value.scale();
- scale = makeScalePositive(scale, val);
- String fieldType = getFieldType(field.getFieldAttribute());
- String result = format(this.addr, val.toString(), field, fieldType, null, scale);
- return buffer.append(result);
- }
-
- public StringBuffer formatBigInteger(BigInteger value, StringBuffer buffer, FieldPosition field) {
- if (buffer == null || field == null) {
- throw new NullPointerException();
- }
- String fieldType = getFieldType(field.getFieldAttribute());
- String result = format(this.addr, value.toString(10), field, fieldType, null, 0);
- return buffer.append(result);
- }
-
- public StringBuffer format(long value, StringBuffer buffer, FieldPosition field) {
- if (buffer == null || field == null) {
- throw new NullPointerException();
- }
- String fieldType = getFieldType(field.getFieldAttribute());
- buffer.append(format(this.addr, value, field, fieldType, null));
- return buffer;
- }
-
- public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
- if (buffer == null || field == null) {
- throw new NullPointerException();
- }
- String fieldType = getFieldType(field.getFieldAttribute());
- buffer.append(format(this.addr, value, field, fieldType, null));
- return buffer;
- }
-
- public void applyLocalizedPattern(String pattern) {
- applyPattern(this.addr, true, pattern);
- lastPattern = null;
- }
-
- public void applyPattern(String pattern) {
- if (lastPattern != null && pattern.equals(lastPattern)) {
- return;
- }
- applyPattern(this.addr, false, pattern);
- lastPattern = pattern;
- }
-
- public AttributedCharacterIterator formatToCharacterIterator(Object object) {
- if (!(object instanceof Number)) {
- throw new IllegalArgumentException();
- }
- Number number = (Number) object;
- String text = null;
- StringBuffer attributes = new StringBuffer();
-
- if(number instanceof BigInteger) {
- BigInteger valBigInteger = (BigInteger) number;
- text = format(this.addr, valBigInteger.toString(10), null, null, attributes, 0);
- } else if(number instanceof BigDecimal) {
- BigDecimal valBigDecimal = (BigDecimal) number;
- if (getMultiplier() != 1) {
- valBigDecimal = applyMultiplier(valBigDecimal);
- }
- StringBuilder val = new StringBuilder();
- val.append(valBigDecimal.unscaledValue().toString(10));
- int scale = valBigDecimal.scale();
- scale = makeScalePositive(scale, val);
- text = format(this.addr, val.toString(), null, null, attributes, scale);
- } else if (number instanceof Double || number instanceof Float) {
- double dv = number.doubleValue();
- text = format(this.addr, dv, null, null, attributes);
- } else {
- long lv = number.longValue();
- text = format(this.addr, lv, null, null, attributes);
- }
-
- AttributedString as = new AttributedString(text);
-
- String[] attrs = attributes.toString().split(";");
- // add NumberFormat field attributes to the AttributedString
- int size = attrs.length / 3;
- if(size * 3 != attrs.length) {
- return as.getIterator();
- }
- for (int i = 0; i < size; i++) {
- Format.Field attribute = getField(attrs[3*i]);
- as.addAttribute(attribute, attribute, Integer.parseInt(attrs[3*i+1]),
- Integer.parseInt(attrs[3*i+2]));
- }
-
- // return the CharacterIterator from AttributedString
- return as.getIterator();
- }
-
- private int makeScalePositive(int scale, StringBuilder val) {
- if (scale < 0) {
- scale = -scale;
- for (int i = scale; i > 0; i--) {
- val.append('0');
- }
- scale = 0;
- }
- return scale;
- }
-
- public String toLocalizedPattern() {
- return toPatternImpl(this.addr, true);
- }
-
- public String toPattern() {
- return toPatternImpl(this.addr, false);
- }
-
- public Number parse(String string, ParsePosition position) {
- return parse(addr, string, position);
- }
-
- // start getter and setter
-
- public int getMaximumFractionDigits() {
- return getAttribute(this.addr, UNUM_MAX_FRACTION_DIGITS);
- }
-
- public int getMaximumIntegerDigits() {
- return getAttribute(this.addr, UNUM_MAX_INTEGER_DIGITS);
- }
-
- public int getMinimumFractionDigits() {
- return getAttribute(this.addr, UNUM_MIN_FRACTION_DIGITS);
- }
-
- public int getMinimumIntegerDigits() {
- return getAttribute(this.addr, UNUM_MIN_INTEGER_DIGITS);
- }
-
- public int getGroupingSize() {
- return getAttribute(this.addr, UNUM_GROUPING_SIZE);
- }
-
- public int getMultiplier() {
- return getAttribute(this.addr, UNUM_MULTIPLIER);
- }
-
- public String getNegativePrefix() {
- if (negPrefNull) {
- return null;
- }
- return getTextAttribute(this.addr, UNUM_NEGATIVE_PREFIX);
- }
-
- public String getNegativeSuffix() {
- if (negSuffNull) {
- return null;
- }
- return getTextAttribute(this.addr, UNUM_NEGATIVE_SUFFIX);
- }
-
- public String getPositivePrefix() {
- if (posPrefNull) {
- return null;
- }
- return getTextAttribute(this.addr, UNUM_POSITIVE_PREFIX);
- }
-
- public String getPositiveSuffix() {
- if (posSuffNull) {
- return null;
- }
- return getTextAttribute(this.addr, UNUM_POSITIVE_SUFFIX);
- }
-
- public boolean isDecimalSeparatorAlwaysShown() {
- return getAttribute(this.addr, UNUM_DECIMAL_ALWAYS_SHOWN) != 0;
- }
-
- public boolean isParseIntegerOnly() {
- return getAttribute(this.addr, UNUM_PARSE_INT_ONLY) != 0;
- }
-
- public boolean isGroupingUsed() {
- return getAttribute(this.addr, UNUM_GROUPING_USED) != 0;
- }
-
- public void setDecimalSeparatorAlwaysShown(boolean value) {
- int i = value ? -1 : 0;
- setAttribute(this.addr, UNUM_DECIMAL_ALWAYS_SHOWN, i);
- }
-
- public void setCurrency(Currency currency) {
- setSymbol(this.addr, UNUM_CURRENCY_SYMBOL, currency.getSymbol());
- setSymbol(this.addr, UNUM_INTL_CURRENCY_SYMBOL, currency.getCurrencyCode());
- }
-
- public void setGroupingSize(int value) {
- setAttribute(this.addr, UNUM_GROUPING_SIZE, value);
- }
-
- public void setGroupingUsed(boolean value) {
- int i = value ? -1 : 0;
- setAttribute(this.addr, UNUM_GROUPING_USED, i);
- }
-
- public void setMaximumFractionDigits(int value) {
- setAttribute(this.addr, UNUM_MAX_FRACTION_DIGITS, value);
- }
-
- public void setMaximumIntegerDigits(int value) {
- setAttribute(this.addr, UNUM_MAX_INTEGER_DIGITS, value);
- }
-
- public void setMinimumFractionDigits(int value) {
- setAttribute(this.addr, UNUM_MIN_FRACTION_DIGITS, value);
- }
-
- public void setMinimumIntegerDigits(int value) {
- setAttribute(this.addr, UNUM_MIN_INTEGER_DIGITS, value);
- }
-
- public void setMultiplier(int value) {
- setAttribute(this.addr, UNUM_MULTIPLIER, value);
- // Update the cached BigDecimal for multiplier.
- multiplierBigDecimal = BigDecimal.valueOf(value);
- }
-
- public void setNegativePrefix(String value) {
- negPrefNull = value == null;
- if (!negPrefNull) {
- setTextAttribute(this.addr, UNUM_NEGATIVE_PREFIX, value);
- }
- }
-
- public void setNegativeSuffix(String value) {
- negSuffNull = value == null;
- if (!negSuffNull) {
- setTextAttribute(this.addr, UNUM_NEGATIVE_SUFFIX, value);
- }
- }
-
- public void setPositivePrefix(String value) {
- posPrefNull = value == null;
- if (!posPrefNull) {
- setTextAttribute(this.addr, UNUM_POSITIVE_PREFIX, value);
- }
- }
-
- public void setPositiveSuffix(String value) {
- posSuffNull = value == null;
- if (!posSuffNull) {
- setTextAttribute(this.addr, UNUM_POSITIVE_SUFFIX, value);
- }
- }
-
- public void setParseIntegerOnly(boolean value) {
- int i = value ? -1 : 0;
- setAttribute(this.addr, UNUM_PARSE_INT_ONLY, i);
- }
-
- static protected String getFieldType(Format.Field field) {
- if(field == null) {
- return null;
- }
- if(field.equals(NumberFormat.Field.SIGN)) {
- return "sign";
- }
- if(field.equals(NumberFormat.Field.INTEGER)) {
- return "integer";
- }
- if(field.equals(NumberFormat.Field.FRACTION)) {
- return "fraction";
- }
- if(field.equals(NumberFormat.Field.EXPONENT)) {
- return "exponent";
- }
- if(field.equals(NumberFormat.Field.EXPONENT_SIGN)) {
- return "exponent_sign";
- }
- if(field.equals(NumberFormat.Field.EXPONENT_SYMBOL)) {
- return "exponent_symbol";
- }
- if(field.equals(NumberFormat.Field.CURRENCY)) {
- return "currency";
- }
- if(field.equals(NumberFormat.Field.GROUPING_SEPARATOR)) {
- return "grouping_separator";
- }
- if(field.equals(NumberFormat.Field.DECIMAL_SEPARATOR)) {
- return "decimal_separator";
- }
- if(field.equals(NumberFormat.Field.PERCENT)) {
- return "percent";
- }
- if(field.equals(NumberFormat.Field.PERMILLE)) {
- return "permille";
- }
- return null;
- }
-
- protected Format.Field getField(String type) {
- if(type.equals("")) {
- return null;
- }
- if(type.equals("sign")) {
- return NumberFormat.Field.SIGN;
- }
- if(type.equals("integer")) {
- return NumberFormat.Field.INTEGER;
- }
- if(type.equals("fraction")) {
- return NumberFormat.Field.FRACTION;
- }
- if(type.equals("exponent")) {
- return NumberFormat.Field.EXPONENT;
- }
- if(type.equals("exponent_sign")) {
- return NumberFormat.Field.EXPONENT_SIGN;
- }
- if(type.equals("exponent_symbol")) {
- return NumberFormat.Field.EXPONENT_SYMBOL;
- }
- if(type.equals("currency")) {
- return NumberFormat.Field.CURRENCY;
- }
- if(type.equals("grouping_separator")) {
- return NumberFormat.Field.GROUPING_SEPARATOR;
- }
- if(type.equals("decimal_separator")) {
- return NumberFormat.Field.DECIMAL_SEPARATOR;
- }
- if(type.equals("percent")) {
- return NumberFormat.Field.PERCENT;
- }
- if(type.equals("permille")) {
- return NumberFormat.Field.PERMILLE;
- }
- return null;
- }
-
- private static void applyPattern(int addr, boolean localized, String pattern) {
- try {
- applyPatternImpl(addr, localized, pattern);
- } catch (NullPointerException npe) {
- throw npe;
- } catch (RuntimeException re) {
- throw new IllegalArgumentException("syntax error: " + re.getMessage() + ": " + pattern);
- }
- }
-
- public void setRoundingMode(RoundingMode roundingMode, double roundingIncrement) {
- final int nativeRoundingMode;
- switch (roundingMode) {
- case CEILING: nativeRoundingMode = 0; break;
- case FLOOR: nativeRoundingMode = 1; break;
- case DOWN: nativeRoundingMode = 2; break;
- case UP: nativeRoundingMode = 3; break;
- case HALF_EVEN: nativeRoundingMode = 4; break;
- case HALF_DOWN: nativeRoundingMode = 5; break;
- case HALF_UP: nativeRoundingMode = 6; break;
- default: throw new AssertionError();
- }
- setRoundingMode(addr, nativeRoundingMode, roundingIncrement);
- }
-
- private static native void applyPatternImpl(int addr, boolean localized, String pattern);
- private static native int cloneDecimalFormatImpl(int addr);
- private static native void closeDecimalFormatImpl(int addr);
- private static native String format(int addr, long value, FieldPosition position, String fieldType, StringBuffer attributes);
- private static native String format(int addr, double value, FieldPosition position, String fieldType, StringBuffer attributes);
- private static native String format(int addr, String value, FieldPosition position, String fieldType, StringBuffer attributes, int scale);
- private static native int getAttribute(int addr, int symbol);
- private static native String getTextAttribute(int addr, int symbol);
- private static native int openDecimalFormatImpl(String pattern, String currencySymbol,
- char decimalSeparator, char digit, char groupingSeparator, String infinity,
- String internationalCurrencySymbol, char minusSign, char monetaryDecimalSeparator,
- String nan, char patternSeparator, char percent, char perMill, char zeroDigit);
- private static native Number parse(int addr, String string, ParsePosition position);
- private static native void setDecimalFormatSymbols(int addr, String currencySymbol,
- char decimalSeparator, char digit, char groupingSeparator, String infinity,
- String internationalCurrencySymbol, char minusSign, char monetaryDecimalSeparator,
- String nan, char patternSeparator, char percent, char perMill, char zeroDigit);
- private static native void setSymbol(int addr, int symbol, String str);
- private static native void setAttribute(int addr, int symbol, int i);
- private static native void setRoundingMode(int addr, int roundingMode, double roundingIncrement);
- private static native void setTextAttribute(int addr, int symbol, String str);
- private static native String toPatternImpl(int addr, boolean localized);
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/NativeIDN.java b/icu/src/main/java/com/ibm/icu4jni/text/NativeIDN.java
deleted file mode 100644
index b973131..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/NativeIDN.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.text;
-
-public class NativeIDN {
- public static String toASCII(String s, int flags) {
- return convert(s, flags, true);
- }
-
- public static String toUnicode(String s, int flags) {
- try {
- return convert(s, flags, false);
- } catch (IllegalArgumentException ex) {
- // The RI documentation explicitly states that this method can't fail.
- // ICU4C disagrees, as does the RI in practice.
- // The RI just returns the input string if it can't
- return s;
- }
- }
-
- private static String convert(String s, int flags, boolean toAscii) {
- if (s == null) {
- throw new NullPointerException();
- }
- return convertImpl(s, flags, toAscii);
- }
- private static native String convertImpl(String s, int flags, boolean toAscii);
-
- private NativeIDN() {}
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/NativeNormalizer.java b/icu/src/main/java/com/ibm/icu4jni/text/NativeNormalizer.java
deleted file mode 100644
index f14b6c1..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/NativeNormalizer.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.text;
-
-import java.text.Normalizer.Form;
-
-public final class NativeNormalizer {
- public static boolean isNormalized(CharSequence src, Form form) {
- return isNormalizedImpl(src.toString(), toUNormalizationMode(form));
- }
-
- public static String normalize(CharSequence src, Form form) {
- return normalizeImpl(src.toString(), toUNormalizationMode(form));
- }
-
- private static int toUNormalizationMode(Form form) {
- // Translates Java enum constants to ICU int constants.
- // See UNormalizationMode in "unicode/unorm.h". Stable API since ICU 2.0.
- switch (form) {
- case NFC: return 4;
- case NFD: return 2;
- case NFKC: return 5;
- case NFKD: return 3;
- }
- throw new AssertionError("unknown Normalizer.Form " + form);
- }
-
- private static native String normalizeImpl(String src, int form);
-
- private static native boolean isNormalizedImpl(String src, int form);
-
- private NativeNormalizer() {}
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java b/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java
deleted file mode 100644
index 8e048dd..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/text/RuleBasedCollator.java
+++ /dev/null
@@ -1,543 +0,0 @@
-/**
-*******************************************************************************
-* Copyright (C) 1996-2005, International Business Machines Corporation and *
-* others. All Rights Reserved. *
-*******************************************************************************
-*
-*
-*******************************************************************************
-*/
-
-package com.ibm.icu4jni.text;
-
-import java.util.Locale;
-import java.text.CharacterIterator;
-import java.text.ParseException;
-
-/**
-* Concrete implementation class for Collation.
-*
-* < modifier >
-* < relation > < text-argument >
-* < reset > < text-argument >
-*
-* RuleBasedCollator
has the following restrictions for efficiency
-* (other subclasses may be used for more complex languages) :
-*
-*
-*
-* The following demonstrates how to create your own collation rules:
-*
-*
-*
-* b c
is
-* treated as bc
.
-*
-*
-*
-*
-* Notice that the order is important, as the subsequent item goes immediately
-* after the text-argument. The following are not equivalent:
-*
-* a < b < c
-* a < b & b < c
-* a < c & a < b
-*
-*
-*
-* Either the text-argument must already be present in the sequence, or some
-* initial substring of the text-argument must be present. (e.g. "a < b & ae <
-* e" is valid since "a" is present in the sequence before "ae" is reset). In
-* this latter case, "ae" is not entered and treated as a single character;
-* instead, "e" is sorted as if it were expanded to two characters: "a"
-* followed by an "e". This difference appears in natural languages: in
-* traditional Spanish "ch" is treated as though it contracts to a single
-* character (expressed as "c < ch < d"), while in traditional German a-umlaut
-* is treated as though it expanded to two characters (expressed as "a,A < b,B
-* ... & ae;? & AE;?"). [? and ? are, of course, the escape sequences for
-* a-umlaut.]
-*
-* a < b & a < c
-* a < c & a < b
-*
-* RuleBasedCollator
automatically processes its rule table to
-* include both pre-composed and combining-character versions of accented
-* characters. Even if the provided rule string contains only base characters
-* and separate combining accent characters, the pre-composed accented
-* characters matching all canonical combinations of characters from the rule
-* string will be entered in the table.
-*
-*
-* If you produce one of these errors, a RuleBasedCollator
throws
-* a ParseException
.
-*
-* Collator
's factory method getInstance
.
-* However, to create a rule-based Collator object with specialized rules
-* tailored to your needs, you construct the RuleBasedCollator
-* with the rules contained in a String
object. For example:
-*
-*
-* Or:
-*
-* String Simple = "< a < b < c < d";
-* RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
-*
-*
-*
-*
-*
-* String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
-* "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
-* "< u,U< v,V< w,W< x,X< y,Y< z,Z" +
-* "< ?=a?,?=A?" +
-* ";aa,AA< ?,?< ?,?";
-* RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
-*
-* Collator
s is as simple as concatenating strings.
-* Here's an example that combines two Collator
s from two
-* different locales:
-*
-*
-*
-*
-* // Create an en_US Collator object
-* RuleBasedCollator en_USCollator = (RuleBasedCollator)
-* Collator.getInstance(new Locale("en", "US", ""));
-* // Create a da_DK Collator object
-* RuleBasedCollator da_DKCollator = (RuleBasedCollator)
-* Collator.getInstance(new Locale("da", "DK", ""));
-* // Combine the two
-* // First, get the collation rules from en_USCollator
-* String en_USRules = en_USCollator.getRules();
-* // Second, get the collation rules from da_DKCollator
-* String da_DKRules = da_DKCollator.getRules();
-* RuleBasedCollator newCollator =
-* new RuleBasedCollator(en_USRules + da_DKRules);
-* // newCollator has the combined rules
-*
-* Collator
object. For example, add
-* "& C < ch, cH, Ch, CH" to the en_USCollator
object to create
-* your own:
-*
-*
-*
-*
-* // Create a new Collator object with additional rules
-* String addRules = "& C < ch, cH, Ch, CH";
-* RuleBasedCollator myCollator =
-* new RuleBasedCollator(en_USCollator + addRules);
-* // myCollator contains the new rules
-*
-*
-*
-*
-*
-* // old rule
-* String oldRules = "=?;?;?" // main accents Diaeresis 00A8, Macron 00AF
-* // Acute 00BF
-* + "< a , A ; ae, AE ; ? , ?"
-* + "< b , B < c, C < e, E & C < d, D";
-* // change the order of accent characters
-* String addOn = "& ?;?;?;"; // Acute 00BF, Macron 00AF, Diaeresis 00A8
-* RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
-*
-* Collator
, you
-* can either sort English characters before or after Japanese characters,
-*
-*
-*
-* // get en_US Collator rules
-* RuleBasedCollator en_USCollator =
-* (RuleBasedCollator)Collator.getInstance(Locale.US);
-* // add a few Japanese character to sort before English characters
-* // suppose the last character before the first base letter 'a' in
-* // the English collation rule is ?
-* String jaString = "& \\u30A2 , \\u30FC < \\u30C8";
-* RuleBasedCollator myJapaneseCollator = new
-* RuleBasedCollator(en_USCollator.getRules() + jaString);
-*
-*
- *
- * Collator myCollation = Collator.createInstance(Locale::US);
- * myCollation.setStrength(CollationAttribute.VALUE_PRIMARY);
- * // result would be 0 ("abc" == "ABC")
- * // (no primary difference between "abc" and "ABC")
- * int result = myCollation.compare("abc", "ABC",3);
- * myCollation.setStrength(CollationAttribute.VALUE_TERTIARY);
- * // result would be -1 (abc" <<< "ABC")
- * // (with tertiary difference between "abc" and "ABC")
- * int result = myCollation.compare("abc", "ABC",3);
- *
- */
- public int compare(String source, String target) {
- return NativeCollation.compare(m_collator_, source, target);
- }
-
- /**
- * Get the normalization mode for this object.
- * The normalization mode influences how strings are compared.
- * @see #CANONICAL_DECOMPOSITION
- * @see #NO_DECOMPOSITION
- * @stable ICU 2.4
- */
- public int getDecomposition() {
- return NativeCollation.getNormalization(m_collator_);
- }
-
- /**
- *
- * E.g. with strength == CollationAttribute.VALUE_SECONDARY, the tertiary difference - * is ignored - *
- *- * E.g. with strength == PRIMARY, the secondary and tertiary difference are - * ignored. - *
- * @return the current comparison level. - * @see #PRIMARY - * @see #SECONDARY - * @see #TERTIARY - * @see #QUATERNARY - * @see #IDENTICAL - * @stable ICU 2.4 - */ - public int getStrength() { - return NativeCollation.getAttribute(m_collator_, CollationAttribute.STRENGTH); - } - - /** - * Sets the minimum strength to be used in comparison or transformation. - *Example of use:
- *
- *
- * Collator myCollation = Collator.createInstance(Locale::US);
- * myCollation.setStrength(PRIMARY);
- * // result will be "abc" == "ABC"
- * // tertiary differences will be ignored
- * int result = myCollation->compare("abc", "ABC");
- *
- * @param strength the new comparison level.
- * @exception IllegalArgumentException when argument does not belong to any collation strength
- * mode or error occurs while setting data.
- * @see #PRIMARY
- * @see #SECONDARY
- * @see #TERTIARY
- * @see #QUATERNARY
- * @see #IDENTICAL
- * @stable ICU 2.4
- */
- public void setStrength(int strength) {
- NativeCollation.setAttribute(m_collator_, CollationAttribute.STRENGTH, strength);
- }
-
- /**
- * Sets the attribute to be used in comparison or transformation.
- *
Example of use:
- *
- *
- * Collator myCollation = Collator.createInstance(Locale::US);
- * myCollation.setAttribute(CollationAttribute.CASE_LEVEL,
- * CollationAttribute.VALUE_ON);
- * int result = myCollation->compare("\\u30C3\\u30CF",
- * "\\u30C4\\u30CF");
- * // result will be -1
- *
- * @param type the attribute to be set from CollationAttribute
- * @param value attribute value from CollationAttribute
- * @stable ICU 2.4
- */
- public void setAttribute(int type, int value) {
- NativeCollation.setAttribute(m_collator_, type, value);
- }
-
- /**
- * Gets the attribute to be used in comparison or transformation.
- * @param type the attribute to be set from CollationAttribute
- * @return value attribute value from CollationAttribute
- * @stable ICU 2.4
- */
- public int getAttribute(int type) {
- return NativeCollation.getAttribute(m_collator_, type);
- }
-
- public CollationKey getCollationKey(String source) {
- if (source == null) {
- return null;
- }
- byte[] key = NativeCollation.getSortKey(m_collator_, source);
- if (key == null) {
- return null;
- }
- return new CollationKey(source, key);
- }
-
- /**
- * Get the collation rules of this Collation object
- * The rules will follow the rule syntax.
- * @return collation rules.
- * @stable ICU 2.4
- */
- public String getRules() {
- return NativeCollation.getRules(m_collator_);
- }
-
- /**
- * Create a CollationElementIterator object that will iterator over the
- * elements in a string, using the collation rules defined in this
- * RuleBasedCollator
- * @param source string to iterate over
- * @return address of C collationelement
- * @exception IllegalArgumentException thrown when error occurs
- * @stable ICU 2.4
- */
- public CollationElementIterator getCollationElementIterator(String source) {
- CollationElementIterator result = new CollationElementIterator(
- NativeCollation.getCollationElementIterator(m_collator_, source));
- // result.setOwnCollationElementIterator(true);
- return result;
- }
-
- public CollationElementIterator getCollationElementIterator(CharacterIterator it) {
- // We only implement the String-based API, so build a string from the iterator.
- return getCollationElementIterator(characterIteratorToString(it));
- }
-
- private String characterIteratorToString(CharacterIterator it) {
- StringBuilder result = new StringBuilder();
- for (char ch = it.current(); ch != CharacterIterator.DONE; ch = it.next()) {
- result.append(ch);
- }
- return result.toString();
- }
-
- @Override
- public int hashCode() {
- return 42; // No-one uses RuleBasedCollator as a hash key.
- }
-
- /**
- * Checks if argument object is equals to this object.
- * @param target object
- * @return true if source is equivalent to target, false otherwise
- * @stable ICU 2.4
- */
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
- if (!(object instanceof RuleBasedCollator)) {
- return false;
- }
- RuleBasedCollator rhs = (RuleBasedCollator) object;
- return getRules().equals(rhs.getRules()) &&
- getStrength() == rhs.getStrength() &&
- getDecomposition() == rhs.getDecomposition();
- }
-
- RuleBasedCollator(Locale locale) {
- m_collator_ = NativeCollation.openCollator(locale.toString());
- }
-
- @Override
- protected void finalize() {
- NativeCollation.closeCollator(m_collator_);
- }
-
- private RuleBasedCollator(int addr) {
- m_collator_ = addr;
- }
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/util/ICU.java b/icu/src/main/java/com/ibm/icu4jni/util/ICU.java
deleted file mode 100644
index b684068..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/util/ICU.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.util;
-
-import java.util.Locale;
-import java.util.TimeZone;
-import java.util.logging.Logger;
-
-/**
- * Makes ICU data accessible to Java.
- */
-public final class ICU {
- /**
- * Cache for ISO language names.
- */
- private static String[] isoLanguages;
-
- /**
- * Cache for ISO country names.
- */
- private static String[] isoCountries;
-
- /**
- * Available timezones cache.
- */
- private static String[] availableTimezones;
-
- /**
- * Returns an array of ISO language names (two-letter codes), fetched either
- * from ICU's database or from our memory cache.
- *
- * @return The array.
- */
- public static String[] getISOLanguages() {
- if (isoLanguages == null) {
- isoLanguages = getISOLanguagesNative();
- }
- return isoLanguages.clone();
- }
-
- /**
- * Returns an array of ISO country names (two-letter codes), fetched either
- * from ICU's database or from our memory cache.
- *
- * @return The array.
- */
- public static String[] getISOCountries() {
- if (isoCountries == null) {
- isoCountries = getISOCountriesNative();
- }
- return isoCountries.clone();
- }
-
- /**
- * Returns an array of names of timezones that are available in the system,
- * fetched either from the TimeZone class or from our memory cache.
- *
- * @return The array.
- */
- public static String[] getKnownTimezones() {
- if (availableTimezones == null) {
- availableTimezones = TimeZone.getAvailableIDs();
- }
- return availableTimezones.clone();
- }
-
- /**
- * Returns the display name for the given time zone using the given locale.
- *
- * @param id The time zone ID, for example "Europe/Berlin"
- * @param daylight Indicates whether daylight savings is in use
- * @param style The style, 0 for long, 1 for short
- * @param locale The locale name, for example "en_US".
- * @return The desired display name
- */
- public static String getDisplayTimeZone(String id, boolean daylight, int style, String locale) {
- // If we already have the strings, linear search through them is 10x quicker than
- // calling ICU for just the one we want.
- if (DefaultTimeZones.locale.equals(locale)) {
- String result = lookupDisplayTimeZone(DefaultTimeZones.names, id, daylight, style);
- if (result != null) {
- return result;
- }
- }
- return getDisplayTimeZoneNative(id, daylight, style, locale);
- }
-
- public static String lookupDisplayTimeZone(String[][] zoneStrings, String id, boolean daylight, int style) {
- for (String[] row : zoneStrings) {
- if (row[0].equals(id)) {
- if (daylight) {
- return (style == TimeZone.LONG) ? row[3] : row[4];
- } else {
- return (style == TimeZone.LONG) ? row[1] : row[2];
- }
- }
- }
- return null;
- }
-
- /**
- * Initialization holder for default time zone names. This class will
- * be preloaded by the zygote to share the time and space costs of setting
- * up the list of time zone names, so although it looks like the lazy
- * initialization idiom, it's actually the opposite.
- */
- private static class DefaultTimeZones {
- /**
- * Name of default locale at the time this class was initialized.
- */
- private static final String locale = Locale.getDefault().toString();
-
- /**
- * Names of time zones for the default locale.
- */
- private static final String[][] names = createTimeZoneNamesFor(locale);
- }
-
- /**
- * Creates array of time zone names for the given locale. This method takes
- * about 2s to run on a 400MHz ARM11.
- */
- private static String[][] createTimeZoneNamesFor(String locale) {
- long start = System.currentTimeMillis();
-
- /*
- * The following code is optimized for fast native response (the time a
- * method call can be in native code is limited). It prepares an empty
- * array to keep native code from having to create new Java objects. It
- * also fill in the time zone IDs to speed things up a bit. There's one
- * array for each time zone name type. (standard/long, standard/short,
- * daylight/long, daylight/short) The native method that fetches these
- * strings is faster if it can do all entries of one type, before having
- * to change to the next type. That's why the array passed down to
- * native has 5 entries, each providing space for all time zone names of
- * one type. Likely this access to the fields is much faster in the
- * native code because there's less array access overhead.
- */
- String[][] arrayToFill = new String[5][];
- arrayToFill[0] = getKnownTimezones();
- arrayToFill[1] = new String[availableTimezones.length];
- arrayToFill[2] = new String[availableTimezones.length];
- arrayToFill[3] = new String[availableTimezones.length];
- arrayToFill[4] = new String[availableTimezones.length];
-
- /*
- * Fill in the zone names in native.
- */
- getTimeZonesNative(arrayToFill, locale);
-
- /*
- * Finally we need to reorder the entries so we get the expected result.
- */
- String[][] result = new String[availableTimezones.length][5];
- for (int i = 0; i < availableTimezones.length; i++) {
- result[i][0] = arrayToFill[0][i];
- result[i][1] = arrayToFill[1][i];
- result[i][2] = arrayToFill[2][i];
- result[i][3] = arrayToFill[3][i];
- result[i][4] = arrayToFill[4][i];
- }
-
- Logger.global.info("Loaded time zone names for " + locale + " in "
- + (System.currentTimeMillis() - start) + "ms.");
-
- return result;
- }
-
- /**
- * Returns the display names for all given timezones using the given locale.
- *
- * @return An array of time zone strings. Each row represents one time zone.
- * The first columns holds the ID of the time zone, for example
- * "Europe/Berlin". The other columns then hold for each row the
- * four time zone names with and without daylight savings and in
- * long and short format. It's exactly the array layout required by
- * the TimeZone class.
- */
- public static String[][] getDisplayTimeZones(String locale) {
- String defaultLocale = Locale.getDefault().toString();
- if (locale == null) {
- locale = defaultLocale;
- }
-
- // If locale == default and the default locale hasn't changed since
- // DefaultTimeZones loaded, return the cached names.
- // TODO: We should force a reboot if the default locale changes.
- if (defaultLocale.equals(locale) && DefaultTimeZones.locale.equals(defaultLocale)) {
- return clone2dStringArray(DefaultTimeZones.names);
- }
-
- return createTimeZoneNamesFor(locale);
- }
-
- public static String[][] clone2dStringArray(String[][] array) {
- String[][] result = new String[array.length][];
- for (int i = 0; i < array.length; ++i) {
- result[i] = array[i].clone();
- }
- return result;
- }
-
- /**
- * Returns the appropriate {@code Locale} given a {@code String} of the form returned
- * by {@code toString}. This is very lenient, and doesn't care what's between the underscores:
- * this method can parse strings that {@code Locale.toString} won't produce.
- * Used to remove duplication.
- */
- public static Locale localeFromString(String localeName) {
- int first = localeName.indexOf('_');
- int second = localeName.indexOf('_', first + 1);
- if (first == -1) {
- // Language only ("ja").
- return new Locale(localeName);
- } else if (second == -1) {
- // Language and country ("ja_JP").
- return new Locale(localeName.substring(0, first), localeName.substring(first + 1));
- } else {
- // Language and country and variant ("ja_JP_TRADITIONAL").
- return new Locale(localeName.substring(0, first), localeName.substring(first + 1, second), localeName.substring(second + 1));
- }
- }
-
- public static Locale[] localesFromStrings(String[] localeNames) {
- Locale[] result = new Locale[localeNames.length];
- for (int i = 0; i < result.length; ++i) {
- result[i] = localeFromString(localeNames[i]);
- }
- return result;
- }
-
- private static Locale[] availableLocalesCache;
- public static Locale[] getAvailableLocales() {
- if (availableLocalesCache == null) {
- availableLocalesCache = localesFromStrings(getAvailableLocalesNative());
- }
- return availableLocalesCache.clone();
- }
-
- public static Locale[] getAvailableBreakIteratorLocales() {
- return localesFromStrings(getAvailableBreakIteratorLocalesNative());
- }
-
- public static Locale[] getAvailableCalendarLocales() {
- return localesFromStrings(getAvailableCalendarLocalesNative());
- }
-
- public static Locale[] getAvailableCollatorLocales() {
- return localesFromStrings(getAvailableCollatorLocalesNative());
- }
-
- public static Locale[] getAvailableDateFormatLocales() {
- return localesFromStrings(getAvailableDateFormatLocalesNative());
- }
-
- public static Locale[] getAvailableDateFormatSymbolsLocales() {
- return getAvailableDateFormatLocales();
- }
-
- public static Locale[] getAvailableDecimalFormatSymbolsLocales() {
- return getAvailableNumberFormatLocales();
- }
-
- public static Locale[] getAvailableNumberFormatLocales() {
- return localesFromStrings(getAvailableNumberFormatLocalesNative());
- }
-
- // --- Native methods accessing ICU's database ----------------------------
-
- private static native String[] getAvailableBreakIteratorLocalesNative();
- private static native String[] getAvailableCalendarLocalesNative();
- private static native String[] getAvailableCollatorLocalesNative();
- private static native String[] getAvailableDateFormatLocalesNative();
- private static native String[] getAvailableLocalesNative();
- private static native String[] getAvailableNumberFormatLocalesNative();
-
- public static native String getCurrencyCodeNative(String locale);
- public static native int getCurrencyFractionDigitsNative(String currencyCode);
- public static native String getCurrencySymbolNative(String locale, String currencyCode);
-
- public static native String getDisplayCountryNative(String countryCode, String locale);
- public static native String getDisplayLanguageNative(String languageCode, String locale);
- public static native String getDisplayVariantNative(String variantCode, String locale);
-
- public static native String getISO3CountryNative(String locale);
- public static native String getISO3LanguageNative(String locale);
-
- private static native String[] getISOLanguagesNative();
- private static native String[] getISOCountriesNative();
-
- private static native void getTimeZonesNative(String[][] arrayToFill, String locale);
-
- private static native String getDisplayTimeZoneNative(String id, boolean isDST, int style,
- String locale);
-
- static native boolean initLocaleDataImpl(String locale, LocaleData result);
-}
diff --git a/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java b/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java
deleted file mode 100644
index e27bd54..0000000
--- a/icu/src/main/java/com/ibm/icu4jni/util/LocaleData.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.ibm.icu4jni.util;
-
-import java.text.DateFormat;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Locale;
-
-/**
- * Passes locale-specific from ICU native code to Java.
- *
- * Note that you share these; you must not alter any of the fields, nor their array elements
- * in the case of arrays. If you ever expose any of these things to user code, you must give
- * them a clone rather than the original.
- */
-public final class LocaleData {
- // A cache for the locale-specific data.
- private static final HashMap
- * These represent an ordinary class or interface as found in the class
- * hierarchy. The name associated with these {@code Class} instances is simply
- * the fully qualified class name of the class or interface that it represents.
- * In addition to this human-readable name, each class is also associated by a
- * so-called signature, which is the letter "L", followed by the
- * class name and a semicolon (";"). The signature is what the runtime system
- * uses internally for identifying the class (for example in a DEX file).
- *
- * These represent the standard Java primitive types and hence share their
- * names (for example "int" for the {@code int} primitive type). Although it is
- * not possible to create new instances based on these {@code Class} instances,
- * they are still useful for providing reflection information, and as the
- * component type of array classes. There is one {@code Class} instance for each
- * primitive type, and their signatures are:
- *
- *
- * These represent the classes of Java arrays. There is one such {@code Class}
- * instance per combination of array leaf component type and arity (number of
- * dimensions). In this case, the name associated with the {@code Class}
- * consists of one or more left square brackets (one per dimension in the array)
- * followed by the signature of the class representing the leaf component type,
- * which can be either an object type or a primitive type. The signature of a
- * {@code Class} representing an array type is the same as its name. Examples
- * of array class signatures are:
- *
- * If the class has not been loaded so far, it is being loaded and linked
- * first. This is done through either the class loader of the calling class
- * or one of its parent class loaders. The class is also being initialized,
- * which means that a possible static initializer block is executed.
- *
- * @param className
- * the name of the non-primitive-type class to find.
- * @return the named {@code Class} instance.
- * @throws ClassNotFoundException
- * if the requested class can not be found.
- * @throws LinkageError
- * if an error occurs during linkage
- * @throws ExceptionInInitializerError
- * if an exception occurs during static initialization of a
- * class.
- */
- public static Class> forName(String className) throws ClassNotFoundException {
- return forName(className, true, VMStack.getCallingClassLoader());
- }
-
- /**
- * Returns a {@code Class} object which represents the class with the
- * specified name. The name should be the name of a class as described in
- * the {@link Class class definition}, however {@code Class}es representing
- * primitive types can not be found using this method. Security rules will
- * be obeyed.
- *
- * If the class has not been loaded so far, it is being loaded and linked
- * first. This is done through either the specified class loader or one of
- * its parent class loaders. The caller can also request the class to be
- * initialized, which means that a possible static initializer block is
- * executed.
- *
- * @param className
- * the name of the non-primitive-type class to find.
- * @param initializeBoolean
- * indicates whether the class should be initialized.
- * @param classLoader
- * the class loader to use to load the class.
- * @return the named {@code Class} instance.
- * @throws ClassNotFoundException
- * if the requested class can not be found.
- * @throws LinkageError
- * if an error occurs during linkage
- * @throws ExceptionInInitializerError
- * if an exception occurs during static initialization of a
- * class.
- */
- public static Class> forName(String className, boolean initializeBoolean,
- ClassLoader classLoader) throws ClassNotFoundException {
-
- if (classLoader == null) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- ClassLoader calling = VMStack.getCallingClassLoader();
- if (calling != null) {
- smgr.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
- classLoader = ClassLoader.getSystemClassLoader();
- }
- // Catch an Exception thrown by the underlying native code. It wraps
- // up everything inside a ClassNotFoundException, even if e.g. an
- // Error occurred during initialization. This as a workaround for
- // an ExceptionInInitilaizerError that's also wrapped. It is actually
- // expected to be thrown. Maybe the same goes for other errors.
- // Not wrapping up all the errors will break android though.
- Class> result;
- try {
- result = classForName(className, initializeBoolean,
- classLoader);
- } catch (ClassNotFoundException e) {
- Throwable cause = e.getCause();
- if (cause instanceof ExceptionInInitializerError) {
- throw (ExceptionInInitializerError) cause;
- }
- throw e;
- }
- return result;
- }
-
- /*
- * Returns a class by name without any security checks.
- *
- * @param className The name of the non-primitive type class to find
- * @param initializeBoolean A boolean indicating whether the class should be
- * initialized
- * @param classLoader The class loader to use to load the class
- * @return the named class.
- * @throws ClassNotFoundException If the class could not be found
- */
- static native Class> classForName(String className, boolean initializeBoolean,
- ClassLoader classLoader) throws ClassNotFoundException;
-
- /**
- * Returns an array containing {@code Class} objects for all public classes
- * and interfaces that are members of this class. This includes public
- * members inherited from super classes and interfaces. If there are no such
- * class members or if this object represents a primitive type then an array
- * of length 0 is returned.
- *
- * @return the public class members of the class represented by this object.
- * @throws SecurityException
- * if a security manager exists and it does not allow member
- * access.
- */
- public Class[] getClasses() {
- // BEGIN android-note
- // trying to get closer to the RI which returns a raw class array.
- // copied from newer version of harmony
- // END android-note
- checkPublicMemberAccess();
- return getFullListOfClasses(true);
- }
-
- /**
- * Returns the annotation of the given type. If there is no such annotation
- * then the method returns {@code null}.
- *
- * @param annotationClass
- * the annotation type.
- * @return the annotation of the given type, or {@code null} if there is no
- * such annotation.
- */
- @SuppressWarnings("unchecked")
- public A getAnnotation(Class annotationClass) {
- Annotation[] list = getAnnotations();
- for (int i = 0; i < list.length; i++) {
- if (annotationClass.isInstance(list[i])) {
- return (A)list[i];
- }
- }
-
- return null;
- }
-
- /**
- * Returns all the annotations of this class. If there are no annotations
- * then an empty array is returned.
- *
- * @return a copy of the array containing this class' annotations.
- * @see #getDeclaredAnnotations()
- */
- public Annotation[] getAnnotations() {
- /*
- * We need to get the annotations declared on this class, plus the
- * annotations from superclasses that have the "@Inherited" annotation
- * set. We create a temporary map to use while we accumulate the
- * annotations and convert it to an array at the end.
- *
- * It's possible to have duplicates when annotations are inherited.
- * We use a Map to filter those out.
- *
- * HashMap might be overkill here.
- */
- HashMap
- * If there are no public fields or if this class represents an array class,
- * a primitive type or {@code void} then an empty array is returned.
- *
- * If there are no public methods or if this {@code Class} represents a
- * primitive type or {@code void} then an empty array is returned.
- * Note: Because of the {@code getCallingClassLoader2()}
- * check, this method must be called exactly one level deep into a
- * public method on this instance. Note: Because of the {@code getCallingClassLoader2()}
- * check, this method must be called exactly one level deep into a
- * public method on this instance.
- * Note: In order to conserve space in an embedded target like Android, we
- * allow this method to return {@code null} for classes in the system
- * protection domain (that is, for system classes). System classes are
- * always given full permissions (that is, AllPermission). This can not be
- * changed through the {@link java.security.Policy} class.
- * Note: This method is implemented in native code, and,
- * as such, is less efficient than using {@link ClassCache#REFLECT}
- * to achieve the same goal. This method exists solely to help
- * bootstrap the reflection bridge. Note: None of the methods perform access checks. It is up
- * to the (package internal) clients of this code to perform such
- * checks as necessary. Also Note: None of the returned array values are
- * protected in any way. It is up to the (again, package internal)
- * clients of this code to protect the arrays if they should ever
- * escape the package. TODO: Take into account assignment compatibility? Note: In such cases, it is insufficient to just make
- * a shallow copy of the array, since method objects aren't
- * immutable due to the existence of {@link
- * AccessibleObject#setAccessible}. Note: In such cases, it is insufficient to just make
- * a shallow copy of the array, since field objects aren't
- * immutable due to the existence of {@link
- * AccessibleObject#setAccessible}.
- * {@code ClassLoader} is an abstract class that implements the common
- * infrastructure required by all class loaders. Android provides several
- * concrete implementations of the class, with
- * {@link dalvik.system.PathClassLoader} being the one typically used. Other
- * applications may implement subclasses of {@code ClassLoader} to provide
- * special ways for loading classes.
- *
- * Note: In the Android reference implementation, the
- * second parameter of {@link #loadClass(String, boolean)} is ignored
- * anyway.
- *
- * Note: In the Android reference implementation, the
- * {@code resolve} parameter is ignored; classes are never linked.
- *
- * Note: In the Android reference implementation, this
- * method has no effect.
- *
- * Note that this method has package visibility only. It is defined here to
- * avoid the security manager check in getSystemClassLoader, which would be
- * required to implement this method anywhere else.
- *
- * Returns true if the receiver is ancestor of another class loader. It also
- * returns true if the two class loader are equal.
- *
- * Note that this method has package visibility only. It is defined here to
- * avoid the security manager check in getParent, which would be required to
- * implement this method anywhere else. The method is also required in other
- * places where class loaders are accesses.
- *
- * This implementation always returns {@code null}.
- *
- * This must be provided by the VM vendor. It is used by
- * SecurityManager.checkMemberAccess() with depth = 3. Note that
- * checkMemberAccess() assumes the following stack when called:
- * Returns the ClassLoader of the method (including natives) at the
- * specified depth on the stack of the calling thread. Frames representing
- * the VM implementation of java.lang.reflect are not included in the list.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * Note: This method does nothing in the Android reference
- * implementation.
- *
- * There a limited chance that we end up with multiple Package objects
- * representing the same package: It can happen when when a package is
- * scattered across different JAR files being loaded by different
- * ClassLoaders. Rather unlikely, and given that this whole thing is more or
- * less a workaround, probably not worth the effort.
- */
- @Override
- protected Package getPackage(String name) {
- if (name != null && !"".equals(name)) {
- synchronized (this) {
- Package pack = super.getPackage(name);
-
- if (pack == null) {
- pack = definePackage(name, "Unknown", "0.0", "Unknown", "Unknown", "0.0",
- "Unknown", null);
- }
-
- return pack;
- }
- }
-
- return null;
- }
-
- @Override
- public URL getResource(String resName) {
- return findResource(resName);
- }
-
- @Override
- protected Class> loadClass(String className, boolean resolve)
- throws ClassNotFoundException {
- Class> clazz = findLoadedClass(className);
-
- if (clazz == null) {
- clazz = findClass(className);
- }
-
- return clazz;
- }
-
- @Override
- public Enumeration
- * {@code Object} provides some fundamental methods for accessing the
- * {@link Class} of an object, getting its {@link #hashCode()}, or checking
- * whether one object {@link #equals(Object)} another. The {@link #toString()}
- * method can be used to convert an object reference into a printable string and
- * is often overridden in subclasses.
- *
- * The {@link #wait()} and {@link #notify()} methods provide a foundation for
- * synchronization, acquiring and releasing an internal monitor associated with
- * each {@code Object}.
- */
-public class Object {
-
- /**
- * Constructs a new instance of {@code Object}.
- */
- public Object() {
- }
-
- /**
- * Creates and returns a copy of this {@code Object}. The default
- * implementation returns a so-called "shallow" copy: It creates a new
- * instance of the same class and then copies the field values (including
- * object references) from this instance to the new instance. A "deep" copy,
- * in contrast, would also recursively clone nested objects. A subclass that
- * needs to implement this kind of cloning should call {@code super.clone()}
- * to create the new instance and then create deep copies of the nested,
- * mutable objects.
- *
- * @return a copy of this object.
- * @throws CloneNotSupportedException
- * if this object's class does not implement the {@code
- * Cloneable} interface.
- */
- protected Object clone() throws CloneNotSupportedException {
- if (!(this instanceof Cloneable)) {
- throw new CloneNotSupportedException("Class doesn't implement Cloneable");
- }
-
- return internalClone((Cloneable) this);
- }
-
- /*
- * Native helper method for cloning.
- */
- private native Object internalClone(Cloneable o);
-
- /**
- * Compares this instance with the specified object and indicates if they
- * are equal. In order to be equal, {@code o} must represent the same object
- * as this instance using a class-specific comparison. The general contract
- * is that this comparison should be both transitive and reflexive.
- *
- * The implementation in {@code Object} returns {@code true} only if {@code
- * o} is the exact same object as the receiver (using the == operator for
- * comparison). Subclasses often implement {@code equals(Object)} so that
- * it takes into account the two object's types and states.
- *
- * The general contract for the {@code equals(Object)} and {@link
- * #hashCode()} methods is that if {@code equals} returns {@code true} for
- * any two objects, then {@code hashCode()} must return the same value for
- * these objects. This means that subclasses of {@code Object} usually
- * override either both methods or none of them.
- *
- * The method can be used to free system resources or perform other cleanup
- * before the object is garbage collected. The default implementation of the
- * method is empty, which is also expected by the VM, but subclasses can
- * override {@code finalize()} as required. Uncaught exceptions which are
- * thrown during the execution of this method cause it to terminate
- * immediately but are otherwise ignored.
- *
- * Note that the VM does guarantee that {@code finalize()} is called at most
- * once for any object, but it doesn't guarantee when (if at all) {@code
- * finalize()} will be called. For example, object B's {@code finalize()}
- * can delay the execution of object A's {@code finalize()} method and
- * therefore it can delay the reclamation of A's memory. To be safe, use a
- * {@link java.lang.ref.ReferenceQueue}, because it provides more control
- * over the way the VM deals with references during garbage collection.
- *
- * As an example, the following code actually compiles, although one might
- * think it shouldn't:
- *
- *
- * This method can only be invoked by a thread which owns this object's
- * monitor. A thread becomes owner of an object's monitor
- *
- * This method can only be invoked by a thread which owns this object's
- * monitor. A thread becomes owner of an object's monitor
- *
- * A waiting thread can be sent {@code interrupt()} to cause it to
- * prematurely stop waiting, so {@code wait} should be called in a loop to
- * check that the condition that has been waited for has been met before
- * continuing.
- *
- * While the thread waits, it gives up ownership of this object's monitor.
- * When it is notified (or interrupted), it re-acquires the monitor before
- * it starts running.
- *
- * A waiting thread can be sent {@code interrupt()} to cause it to
- * prematurely stop waiting, so {@code wait} should be called in a loop to
- * check that the condition that has been waited for has been met before
- * continuing.
- *
- * While the thread waits, it gives up ownership of this object's monitor.
- * When it is notified (or interrupted), it re-acquires the monitor before
- * it starts running.
- *
- * A waiting thread can be sent {@code interrupt()} to cause it to
- * prematurely stop waiting, so {@code wait} should be called in a loop to
- * check that the condition that has been waited for has been met before
- * continuing.
- *
- * While the thread waits, it gives up ownership of this object's monitor.
- * When it is notified (or interrupted), it re-acquires the monitor before
- * it starts running.
- *
- * Packages are managed by class loaders. All classes loaded by the same loader
- * from the same package share a {@code Package} instance.
- * Harmony's native implementation (for comparison purposes):
- * http://tinyurl.com/3ytwuq
- */
-final class ProcessManager {
-
- /**
- * constant communicated from native code indicating that a
- * child died, but it was unable to determine the status
- */
- private static final int WAIT_STATUS_UNKNOWN = -1;
-
- /**
- * constant communicated from native code indicating that there
- * are currently no children to wait for
- */
- private static final int WAIT_STATUS_NO_CHILDREN = -2;
-
- /**
- * constant communicated from native code indicating that a wait()
- * call returned -1 and set an undocumented (and hence unexpected) errno
- */
- private static final int WAIT_STATUS_STRANGE_ERRNO = -3;
-
- /**
- * Initializes native static state.
- */
- static native void staticInitialize();
- static {
- staticInitialize();
- }
-
- /**
- * Map from pid to Process. We keep weak references to the Process objects
- * and clean up the entries when no more external references are left. The
- * process objects themselves don't require much memory, but file
- * descriptors (associated with stdin/out/err in this case) can be
- * a scarce resource.
- */
- private final Map
- * Shutdown hooks are run concurrently and in an unspecified order. Hooks
- * failing due to an unhandled exception are not a problem, but the stack
- * trace might be printed to the console. Once initiated, the whole shutdown
- * process can only be terminated by calling {@code halt()}.
- *
- * If {@link #runFinalizersOnExit(boolean)} has been called with a {@code
- * true} argument, garbage collection and finalization will take place after
- * all hooks are either finished or have failed. Then the virtual machine
- * terminates.
- *
- * It is recommended that shutdown hooks do not do any time-consuming
- * activities, in order to not hold up the shutdown process longer than
- * necessary.
- *
- * @param hook
- * the shutdown hook to register.
- * @throws IllegalArgumentException
- * if the hook has already been started or if it has already
- * been registered.
- * @throws IllegalStateException
- * if the virtual machine is already shutting down.
- * @throws SecurityException
- * if a SecurityManager is registered and the calling code
- * doesn't have the RuntimePermission("shutdownHooks").
- */
- public void addShutdownHook(Thread hook) {
- // Sanity checks
- if (hook == null) {
- throw new NullPointerException("Hook may not be null.");
- }
-
- if (shuttingDown) {
- throw new IllegalStateException("VM already shutting down");
- }
-
- if (hook.hasBeenStarted) {
- throw new IllegalArgumentException("Hook has already been started");
- }
-
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("shutdownHooks"));
- }
-
- synchronized (shutdownHooks) {
- if (shutdownHooks.contains(hook)) {
- throw new IllegalArgumentException("Hook already registered.");
- }
-
- shutdownHooks.add(hook);
- }
- }
-
- /**
- * Unregisters a previously registered virtual machine shutdown hook.
- *
- * @param hook
- * the shutdown hook to remove.
- * @return {@code true} if the hook has been removed successfully; {@code
- * false} otherwise.
- * @throws IllegalStateException
- * if the virtual machine is already shutting down.
- * @throws SecurityException
- * if a SecurityManager is registered and the calling code
- * doesn't have the RuntimePermission("shutdownHooks").
- */
- public boolean removeShutdownHook(Thread hook) {
- // Sanity checks
- if (hook == null) {
- throw new NullPointerException("Hook may not be null.");
- }
-
- if (shuttingDown) {
- throw new IllegalStateException("VM already shutting down");
- }
-
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new RuntimePermission("shutdownHooks"));
- }
-
- synchronized (shutdownHooks) {
- return shutdownHooks.remove(hook);
- }
- }
-
- /**
- * Causes the virtual machine to stop running, and the program to exit.
- * Neither shutdown hooks nor finalizers are run before.
- *
- * @param code
- * the return code. By convention, non-zero return codes indicate
- * abnormal terminations.
- * @throws SecurityException
- * if the current {@code SecurityManager} does not allow the
- * running thread to terminate the virtual machine.
- * @see SecurityManager#checkExit
- * @see #addShutdownHook(Thread)
- * @see #removeShutdownHook(Thread)
- * @see #runFinalizersOnExit(boolean)
- */
- public void halt(int code) {
- // Security checks
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- smgr.checkExit(code);
- }
-
- // Get out of here...
- nativeExit(code, false);
- }
-
- /**
- * Returns the number of processors available to the virtual machine. The
- * Android reference implementation (currently) always returns 1.
- *
- * @return the number of available processors, at least 1.
- */
- public int availableProcessors() {
- return 1;
- }
-
- /**
- * Returns the maximum amount of memory that may be used by the virtual
- * machine, or {@code Long.MAX_VALUE} if there is no such limit.
- *
- * @return the maximum amount of memory that the virtual machine will try to
- * allocate, measured in bytes.
- */
- public native long maxMemory();
-
-}
-
-/*
- * Internal helper class for creating a localized InputStream. A reader
- * wrapped in an InputStream.
- */
-class ReaderInputStream extends InputStream {
-
- private Reader reader;
-
- private Writer writer;
-
- ByteArrayOutputStream out = new ByteArrayOutputStream(256);
-
- private byte[] bytes;
-
- private int nextByte;
-
- private int numBytes;
-
- String encoding = System.getProperty("file.encoding", "UTF-8");
-
- public ReaderInputStream(InputStream stream) {
- try {
- reader = new InputStreamReader(stream, "UTF-8");
- writer = new OutputStreamWriter(out, encoding);
- } catch (UnsupportedEncodingException e) {
- // Should never happen, since UTF-8 and platform encoding must be
- // supported.
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public int read() throws IOException {
- if (nextByte >= numBytes) {
- readBuffer();
- }
-
- return (numBytes < 0) ? -1 : bytes[nextByte++];
- }
-
- private void readBuffer() throws IOException {
- char[] chars = new char[128];
- int read = reader.read(chars);
- if (read < 0) {
- numBytes = read;
- return;
- }
-
- writer.write(chars, 0, read);
- writer.flush();
- bytes = out.toByteArray();
- numBytes = bytes.length;
- nextByte = 0;
- }
-
-}
-
-/*
- * Internal helper class for creating a localized OutputStream. A writer
- * wrapped in an OutputStream. Bytes are written to characters in big-endian
- * fashion.
- */
-class WriterOutputStream extends OutputStream {
-
- private Reader reader;
-
- private Writer writer;
-
- private PipedOutputStream out;
-
- private PipedInputStream pipe;
-
- private int numBytes;
-
- private String enc = System.getProperty("file.encoding", "UTF-8");
-
- public WriterOutputStream(OutputStream stream) {
- try {
- // sink
- this.writer = new OutputStreamWriter(stream, enc);
-
- // transcriber
- out = new PipedOutputStream();
- pipe = new PipedInputStream(out);
- this.reader = new InputStreamReader(pipe, "UTF-8");
-
- } catch (UnsupportedEncodingException e) {
- // Should never happen, since platform encoding must be supported.
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void write(int b) throws IOException {
- out.write(b);
- if( ++numBytes > 256) {
- flush();
- numBytes = 0;
- }
- }
-
- @Override
- public void flush() throws IOException {
- out.flush();
- char[] chars = new char[128];
- if (pipe.available() > 0) {
- int read = reader.read(chars);
- if (read > 0) {
- writer.write(chars, 0, read);
- }
- }
- writer.flush();
- }
-
- @Override
- public void close() throws IOException {
- out.close();
- flush();
- writer.close();
- }
-}
diff --git a/luni-kernel/src/main/java/java/lang/StackTraceElement.java b/luni-kernel/src/main/java/java/lang/StackTraceElement.java
deleted file mode 100644
index 88fe1ab..0000000
--- a/luni-kernel/src/main/java/java/lang/StackTraceElement.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang;
-
-import java.io.Serializable;
-
-/**
- * A representation of a single stack frame. Arrays of {@code StackTraceElement}
- * are stored in {@link Throwable} objects to represent the whole state of the
- * call stack at the time a {@code Throwable} gets thrown.
- *
- * @see Throwable#getStackTrace()
- */
-public final class StackTraceElement implements Serializable {
-
- private static final long serialVersionUID = 6992337162326171013L;
-
- // BEGIN android-added
- private static final int NATIVE_LINE_NUMBER = -2;
- // END android-added
-
- String declaringClass;
-
- String methodName;
-
- String fileName;
-
- int lineNumber;
-
- /**
- * Constructs a new {@code StackTraceElement} for a specified execution
- * point.
- *
- * @param cls
- * the fully qualified name of the class where execution is at.
- * @param method
- * the name of the method where execution is at.
- * @param file
- * The name of the file where execution is at or {@code null}.
- * @param line
- * the line of the file where execution is at, a negative number
- * if unknown or {@code -2} if the execution is in a native
- * method.
- * @throws NullPointerException
- * if {@code cls} or {@code method} is {@code null}.
- */
- public StackTraceElement(String cls, String method, String file, int line) {
- super();
- if (cls == null || method == null) {
- throw new NullPointerException();
- }
- declaringClass = cls;
- methodName = method;
- fileName = file;
- lineNumber = line;
- }
-
- /**
- *
- * Private, nullary constructor for VM use only.
- *
- * The properties currently provided by the virtual machine are:
- *
- * Security managers do not provide a secure environment for
- * executing untrusted code and are unsupported on Android. Untrusted code
- * cannot be safely isolated within the Dalvik VM.
- *
- * @param sm
- * the new security manager.
- * @throws SecurityException
- * if the security manager has already been set and if its
- * checkPermission method does not allow to redefine the
- * security manager.
- */
- public static void setSecurityManager(SecurityManager sm) {
- if (sm != null) {
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * Returns the platform specific file name format for the shared library
- * named by the argument.
- *
- * @param userLibName
- * the name of the library to look up.
- * @return the platform specific filename for the library.
- */
- public static native String mapLibraryName(String userLibName);
-
- /**
- * Sets the value of the named static field in the receiver to the passed in
- * argument.
- *
- * @param fieldName
- * the name of the field to set, one of in, out, or err
- * @param stream
- * the new value of the field
- */
- private static native void setFieldImpl(String fieldName, String signature, Object stream);
-
-}
-
-/**
- * Internal class holding the System properties. Needed by the Dalvik VM for the
- * two native methods. Must not be a local class, since we don't have a System
- * instance.
- */
-class SystemProperties extends Properties {
- // Dummy, just to make the compiler happy.
-
- native void preInit();
-
- native void postInit();
-}
-
-/**
- * Internal class holding the System environment variables. The Java spec
- * mandates that this map be read-only, so we wrap our real map into this one
- * and make sure no one touches the contents. We also check for null parameters
- * and do some (seemingly unnecessary) type casts to fulfill the contract layed
- * out in the spec.
- */
-class SystemEnvironment implements Map {
-
- private Map
- * {@code Thread}s in the same VM interact and synchronize by the use of shared
- * objects and monitors associated with these objects. Synchronized methods and
- * part of the API in {@link Object} also allow {@code Thread}s to cooperate.
- *
- * There are basically two main ways of having a {@code Thread} execute
- * application code. One is providing a new class that extends {@code Thread}
- * and overriding its {@link #run()} method. The other is providing a new
- * {@code Thread} instance with a {@link Runnable} object during its creation.
- * In both cases, the {@link #start()} method must be called to actually execute
- * the new {@code Thread}.
- *
- * Each {@code Thread} has an integer priority that basically determines the
- * amount of CPU time the {@code Thread} gets. It can be set using the
- * {@link #setPriority(int)} method. A {@code Thread} can also be made a daemon,
- * which makes it run in the background. The latter also affects VM termination
- * behavior: the VM does not terminate automatically as long as there are
- * non-daemon threads running.
- *
- * @see java.lang.Object
- * @see java.lang.ThreadGroup
- *
- */
-public class Thread implements Runnable {
-
- private static final int NANOS_PER_MILLI = 1000000;
-
- /** Park states */
- private static class ParkState {
- /** park state indicating unparked */
- private static final int UNPARKED = 1;
-
- /** park state indicating preemptively unparked */
- private static final int PREEMPTIVELY_UNPARKED = 2;
-
- /** park state indicating parked */
- private static final int PARKED = 3;
- }
-
- /**
- * A representation of a thread's state. A given thread may only be in one
- * state at a time.
- */
- public enum State {
- /**
- * The thread has been created, but has never been started.
- */
- NEW,
- /**
- * The thread may be run.
- */
- RUNNABLE,
- /**
- * The thread is blocked and waiting for a lock.
- */
- BLOCKED,
- /**
- * The thread is waiting.
- */
- WAITING,
- /**
- * The thread is waiting for a specified amount of time.
- */
- TIMED_WAITING,
- /**
- * The thread has been terminated.
- */
- TERMINATED
- }
-
- /**
- * The maximum priority value allowed for a thread.
- */
- public final static int MAX_PRIORITY = 10;
-
- /**
- * The minimum priority value allowed for a thread.
- */
- public final static int MIN_PRIORITY = 1;
-
- /**
- * The normal (default) priority value assigned to threads.
- */
- public final static int NORM_PRIORITY = 5;
-
- /* some of these are accessed directly by the VM; do not rename them */
- volatile VMThread vmThread;
- volatile ThreadGroup group;
- volatile boolean daemon;
- volatile String name;
- volatile int priority;
- volatile long stackSize;
- Runnable target;
- private static int count = 0;
-
- /**
- * Holds the thread's ID. We simply count upwards, so
- * each Thread has a unique ID.
- */
- private long id;
-
- /**
- * Normal thread local values.
- */
- ThreadLocal.Values localValues;
-
- /**
- * Inheritable thread local values.
- */
- ThreadLocal.Values inheritableValues;
-
- /**
- * Holds the interrupt action for this Thread, if any.
- *
- * This is required internally by NIO, so even if it looks like it's
- * useless, don't delete it!
- */
- private Runnable interruptAction;
-
- /**
- * Holds the class loader for this Thread, in case there is one.
- */
- private ClassLoader contextClassLoader;
-
- /**
- * Holds the handler for uncaught exceptions in this Thread,
- * in case there is one.
- */
- private UncaughtExceptionHandler uncaughtHandler;
-
- /**
- * Holds the default handler for uncaught exceptions, in case there is one.
- */
- private static UncaughtExceptionHandler defaultUncaughtHandler;
-
- /**
- * Reflects whether this Thread has already been started. A Thread
- * can only be started once (no recycling). Also, we need it to deduce
- * the proper Thread status.
- */
- boolean hasBeenStarted = false;
-
- /** the park state of the thread */
- private int parkState = ParkState.UNPARKED;
-
- /** The synchronization object responsible for this thread parking. */
- private Object parkBlocker;
-
- /**
- * Constructs a new {@code Thread} with no {@code Runnable} object and a
- * newly generated name. The new {@code Thread} will belong to the same
- * {@code ThreadGroup} as the {@code Thread} calling this constructor.
- *
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- */
- public Thread() {
- create(null, null, null, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with a {@code Runnable} object and a
- * newly generated name. The new {@code Thread} will belong to the same
- * {@code ThreadGroup} as the {@code Thread} calling this constructor.
- *
- * @param runnable
- * a {@code Runnable} whose method
- * Returns the stack traces of all the currently live threads and puts them
- * into the given map.
- *
- * If the conditions
- *
- * The
- * The
- * Sets the default uncaught exception handler. This handler is invoked in
- * case any Thread dies due to an unhandled exception.
- *
- * The
- * This is required internally by NIO, so even if it looks like it's
- * useless, don't delete it!
- *
- * @param action the action to be executed when interruption
- */
- @SuppressWarnings("unused")
- private void setInterruptAction(Runnable action) {
- this.interruptAction = action;
- }
-
- /**
- * Sets the name of the Thread.
- *
- * @param threadName the new name for the Thread
- * @throws SecurityException if
- * Sets the uncaught exception handler. This handler is invoked in case this
- * Thread dies due to an unhandled exception.
- * Note that this method will silently ignore any threads that don't fit in the
- * supplied array.
- *
- * @param threads the array into which the {@code Thread}s will be copied
- * @return the number of {@code Thread}s that were copied
- */
- public int enumerate(Thread[] threads) {
- return enumerate(threads, true);
- }
-
- /**
- * Iterates over all active threads in this group (and, optionally, its
- * sub-groups) and stores the threads in the given array. Returns when the
- * array is full or no more threads remain, whichever happens first.
- *
- * Note that this method will silently ignore any threads that don't fit in the
- * supplied array.
- *
- * @param threads the array into which the {@code Thread}s will be copied
- * @param recurse indicates whether {@code Thread}s in subgroups should be
- * recursively copied as well
- * @return the number of {@code Thread}s that were copied
- */
- public int enumerate(Thread[] threads, boolean recurse) {
- return enumerateGeneric(threads, recurse, 0, true);
- }
-
- /**
- * Iterates over all thread groups in this group (and its sub-groups) and
- * and stores the groups in the given array. Returns when the array is full
- * or no more groups remain, whichever happens first.
- *
- * Note that this method will silently ignore any thread groups that don't fit in the
- * supplied array.
- *
- * @param groups the array into which the {@code ThreadGroup}s will be copied
- * @return the number of {@code ThreadGroup}s that were copied
- */
- public int enumerate(ThreadGroup[] groups) {
- return enumerate(groups, true);
- }
-
- /**
- * Iterates over all thread groups in this group (and, optionally, its
- * sub-groups) and stores the groups in the given array. Returns when
- * the array is full or no more groups remain, whichever happens first.
- *
- * Note that this method will silently ignore any thread groups that don't fit in the
- * supplied array.
- *
- * @param groups the array into which the {@code ThreadGroup}s will be copied
- * @param recurse indicates whether {@code ThreadGroup}s in subgroups should be
- * recursively copied as well or not
- * @return the number of {@code ThreadGroup}s that were copied
- */
- public int enumerate(ThreadGroup[] groups, boolean recurse) {
- return enumerateGeneric(groups, recurse, 0, false);
- }
-
- /**
- * Copies into enumeration starting at
- * enumerationIndex all Threads or ThreadGroups in the
- * receiver. If recurse is true, recursively enumerate the
- * elements in subgroups.
- *
- * If the array passed as parameter is too small no exception is thrown -
- * the extra elements are simply not copied.
- *
- * @param enumeration array into which the elements will be copied
- * @param recurse Indicates whether subgroups should be enumerated or not
- * @param enumerationIndex Indicates in which position of the enumeration
- * array we are
- * @param enumeratingThreads Indicates whether we are enumerating Threads or
- * ThreadGroups
- * @return How many elements were enumerated/copied over
- */
- private int enumerateGeneric(Object[] enumeration, boolean recurse, int enumerationIndex,
- boolean enumeratingThreads) {
- checkAccess();
-
- Object[] immediateCollection = enumeratingThreads ? (Object[]) childrenThreads
- : (Object[]) childrenGroups;
- Object syncLock = enumeratingThreads ? childrenThreadsLock : childrenGroupsLock;
-
- synchronized (syncLock) { // Lock this subpart of the tree as we walk
- for (int i = enumeratingThreads ? numThreads : numGroups; --i >= 0;) {
- if (!enumeratingThreads || ((Thread) immediateCollection[i]).isAlive()) {
- if (enumerationIndex >= enumeration.length) {
- return enumerationIndex;
- }
- enumeration[enumerationIndex++] = immediateCollection[i];
- }
- }
- }
-
- if (recurse) { // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- if (enumerationIndex >= enumeration.length) {
- return enumerationIndex;
- }
- enumerationIndex = childrenGroups[i].enumerateGeneric(enumeration, recurse,
- enumerationIndex, enumeratingThreads);
- }
- }
- }
- return enumerationIndex;
- }
-
- /**
- * Returns the maximum allowed priority for a {@code Thread} in this thread group.
- *
- * @return the maximum priority
- *
- * @see #setMaxPriority
- */
- public final int getMaxPriority() {
- return maxPriority;
- }
-
- /**
- * Returns the name of this thread group.
- *
- * @return the group's name
- */
- public final String getName() {
- return name;
- }
-
- /**
- * Returns this thread group's parent {@code ThreadGroup}. It can be null if this
- * is the the root ThreadGroup.
- *
- * @return the parent
- */
- public final ThreadGroup getParent() {
- if (parent != null) {
- parent.checkAccess();
- }
- return parent;
- }
-
- /**
- * Interrupts every {@code Thread} in this group and recursively in all its
- * subgroups.
- *
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
- * @see Thread#interrupt
- */
- public final void interrupt() {
- checkAccess();
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- this.childrenThreads[i].interrupt();
- }
- }
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].interrupt();
- }
- }
- }
-
- /**
- * Checks whether this thread group is a daemon {@code ThreadGroup}.
- *
- * @return true if this thread group is a daemon {@code ThreadGroup}
- *
- * @see #setDaemon
- * @see #destroy
- */
- public final boolean isDaemon() {
- return isDaemon;
- }
-
- /**
- * Checks whether this thread group has already been destroyed.
- *
- * @return true if this thread group has already been destroyed
- * @see #destroy
- */
- public synchronized boolean isDestroyed() {
- return isDestroyed;
- }
-
- /**
- * Outputs to {@code System.out} a text representation of the
- * hierarchy of {@code Thread}s and {@code ThreadGroup}s in this thread group (and recursively).
- * Proper indentation is used to show the nesting of groups inside groups
- * and threads inside groups.
- */
- public void list() {
- // We start in a fresh line
- System.out.println();
- list(0);
- }
-
- /*
- * Outputs to {@code System.out}a text representation of the
- * hierarchy of Threads and ThreadGroups in this thread group (and recursively).
- * The indentation will be four spaces per level of nesting.
- *
- * @param levels How many levels of nesting, so that proper indentation can
- * be output.
- */
- private void list(int levels) {
- for (int i = 0; i < levels; i++) {
- System.out.print(" "); // 4 spaces for each level
- }
-
- // Print the receiver
- System.out.println(this.toString());
-
- // Print the children threads, with 1 extra indentation
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- // children get an extra indentation, 4 spaces for each level
- for (int j = 0; j <= levels; j++) {
- System.out.print(" ");
- }
- System.out.println(this.childrenThreads[i]);
- }
- }
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].list(levels + 1);
- }
- }
- }
-
- /**
- * Checks whether this thread group is a direct or indirect parent group of a
- * given {@code ThreadGroup}.
- *
- * @param g the potential child {@code ThreadGroup}
- * @return true if this thread group is parent of {@code g}
- */
- public final boolean parentOf(ThreadGroup g) {
- while (g != null) {
- if (this == g) {
- return true;
- }
- g = g.parent;
- }
- return false;
- }
-
- /**
- * Removes a {@code Thread} from this group. This should only be visible to class
- * java.lang.Thread, and should only be called when a Thread dies.
- *
- * @param thread Thread to remove
- *
- * @see #add(Thread)
- */
- final void remove(java.lang.Thread thread) {
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- if (childrenThreads[i].equals(thread)) {
- numThreads--;
- System
- .arraycopy(childrenThreads, i + 1, childrenThreads, i, numThreads
- - i);
- childrenThreads[numThreads] = null;
- break;
- }
- }
- }
- destroyIfEmptyDaemon();
- }
-
- /**
- * Removes an immediate subgroup.
- *
- * @param g ThreadGroup to remove
- *
- * @see #add(Thread)
- * @see #add(ThreadGroup)
- */
- private void remove(ThreadGroup g) {
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- if (childrenGroups[i].equals(g)) {
- numGroups--;
- System.arraycopy(childrenGroups, i + 1, childrenGroups, i, numGroups - i);
- childrenGroups[numGroups] = null;
- break;
- }
- }
- }
- destroyIfEmptyDaemon();
- }
-
- /**
- * Resumes every thread in this group and recursively in all its
- * subgroups.
- *
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
- * @see Thread#resume
- * @see #suspend
- *
- * @deprecated Requires deprecated method Thread.resume().
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- public final void resume() {
- checkAccess();
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- this.childrenThreads[i].resume();
- }
- }
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].resume();
- }
- }
- }
-
- /**
- * Sets whether this is a daemon {@code ThreadGroup} or not. Daemon
- * thread groups are automatically destroyed when they become empty.
- *
- * @param isDaemon the new value
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
- *
- * @see #isDaemon
- * @see #destroy
- */
- public final void setDaemon(boolean isDaemon) {
- checkAccess();
- this.isDaemon = isDaemon;
- }
-
- /**
- * Configures the maximum allowed priority for a {@code Thread} in this group and
- * recursively in all its subgroups.
- *
- * A caller can never increase the maximum priority of a thread group.
- * Such an attempt will not result in an exception, it will
- * simply leave the thread group with its current maximum priority.
- *
- * @param newMax the new maximum priority to be set
- *
- * @throws SecurityException if {@code checkAccess()} fails with a
- * SecurityException
- * @throws IllegalArgumentException if the new priority is greater than
- * Thread.MAX_PRIORITY or less than Thread.MIN_PRIORITY
- *
- * @see #getMaxPriority
- */
- public final void setMaxPriority(int newMax) {
- checkAccess();
-
- if (newMax <= this.maxPriority) {
- if (newMax < Thread.MIN_PRIORITY) {
- newMax = Thread.MIN_PRIORITY;
- }
-
- int parentPriority = parent == null ? newMax : parent.getMaxPriority();
- this.maxPriority = parentPriority <= newMax ? parentPriority : newMax;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- // ??? why not maxPriority
- for (int i = 0; i < numGroups; i++) {
- this.childrenGroups[i].setMaxPriority(newMax);
- }
- }
- }
- }
-
- /**
- * Sets the parent {@code ThreadGroup} of this thread group, and adds this
- * thread group to the parent's collection of immediate children (if {@code parent} is
- * not {@code null}).
- *
- * @param parent The parent ThreadGroup, or null to make this thread group
- * the root ThreadGroup
- *
- * @see #getParent
- * @see #parentOf
- */
- private void setParent(ThreadGroup parent) {
- if (parent != null) {
- parent.add(this);
- }
- this.parent = parent;
- }
-
- /**
- * Stops every thread in this group and recursively in all its subgroups.
- *
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
- * @see Thread#stop()
- * @see Thread#stop(Throwable)
- * @see ThreadDeath
- *
- * @deprecated Requires deprecated method Thread.stop().
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- public final void stop() {
- if (stopHelper()) {
- Thread.currentThread().stop();
- }
- }
-
- /**
- * @deprecated Requires deprecated method Thread.suspend().
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- private final boolean stopHelper() {
- checkAccess();
-
- boolean stopCurrent = false;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- Thread current = Thread.currentThread();
- for (int i = 0; i < numThreads; i++) {
- if (this.childrenThreads[i] == current) {
- stopCurrent = true;
- } else {
- this.childrenThreads[i].stop();
- }
- }
- }
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- stopCurrent |= this.childrenGroups[i].stopHelper();
- }
- }
- return stopCurrent;
- }
-
- /**
- * Suspends every thread in this group and recursively in all its
- * subgroups.
- *
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- *
- * @see Thread#suspend
- * @see #resume
- *
- * @deprecated Requires deprecated method Thread.suspend().
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- public final void suspend() {
- if (suspendHelper()) {
- Thread.currentThread().suspend();
- }
- }
-
- /**
- * @deprecated Requires deprecated method Thread.suspend().
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- private final boolean suspendHelper() {
- checkAccess();
-
- boolean suspendCurrent = false;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- Thread current = Thread.currentThread();
- for (int i = 0; i < numThreads; i++) {
- if (this.childrenThreads[i] == current) {
- suspendCurrent = true;
- } else {
- this.childrenThreads[i].suspend();
- }
- }
- }
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- suspendCurrent |= this.childrenGroups[i].suspendHelper();
- }
- }
- return suspendCurrent;
- }
-
- @Override
- public String toString() {
- return getClass().getName() + "[name=" + this.getName() + ",maxPriority="
- + this.getMaxPriority() + "]";
- }
-
- /**
- * Handles uncaught exceptions. Any uncaught exception in any {@code Thread}
- * is forwarded to the thread's {@code ThreadGroup} by invoking this
- * method.
- *
- * New code should use {@link Thread#setUncaughtExceptionHandler} instead of thread groups.
- *
- * @param t the Thread that terminated with an uncaught exception
- * @param e the uncaught exception itself
- */
- public void uncaughtException(Thread t, Throwable e) {
- // BEGIN android-changed
- if (parent != null) {
- parent.uncaughtException(t, e);
- } else if (Thread.getDefaultUncaughtExceptionHandler() != null) {
- // TODO The spec is unclear regarding this. What do we do?
- Thread.getDefaultUncaughtExceptionHandler().uncaughtException(t, e);
- } else if (!(e instanceof ThreadDeath)) {
- // No parent group, has to be 'system' Thread Group
- e.printStackTrace(System.err);
- }
- // END android-changed
- }
-
- // BEGIN android-added
- /**
- * Non-standard method for adding a thread to a group, required by Dalvik.
- *
- * @param thread Thread to add
- *
- * @throws IllegalThreadStateException if the thread has been destroyed
- * already
- *
- * @see #add(java.lang.Thread)
- * @see #removeThread(java.lang.Thread)
- */
- void addThread(Thread thread) throws IllegalThreadStateException {
- add(thread);
- }
-
- /**
- * Non-standard method for adding a thread to a group, required by Dalvik.
- *
- * @param thread Thread to add
- *
- * @throws IllegalThreadStateException if the thread has been destroyed
- * already
- *
- * @see #remove(java.lang.Thread)
- * @see #addThread(java.lang.Thread)
- */
- void removeThread(Thread thread) throws IllegalThreadStateException {
- remove(thread);
- }
- // END android-added
-}
diff --git a/luni-kernel/src/main/java/java/lang/Throwable.java b/luni-kernel/src/main/java/java/lang/Throwable.java
deleted file mode 100644
index c94631b..0000000
--- a/luni-kernel/src/main/java/java/lang/Throwable.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang;
-
-import java.io.IOException;
-import java.io.ObjectOutputStream;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-
-/**
- * The superclass of all classes which can be thrown by the virtual machine. The
- * two direct subclasses are recoverable exceptions ({@code Exception}) and
- * unrecoverable errors ({@code Error}). This class provides common methods for
- * accessing a string message which provides extra information about the
- * circumstances in which the {@code Throwable} was created (basically an error
- * message in most cases), and for saving a stack trace (that is, a record of
- * the call stack at a particular point in time) which can be printed later.
- *
- * A {@code Throwable} can also include a cause, which is a nested {@code
- * Throwable} that represents the original problem that led to this {@code
- * Throwable}. It is often used for wrapping various types of errors into a
- * common {@code Throwable} without losing the detailed original error
- * information. When printing the stack trace, the trace of the cause is
- * included.
- *
- * @see Error
- * @see Exception
- * @see RuntimeException
- */
-public class Throwable implements java.io.Serializable {
- private static final long serialVersionUID = -3042686055658047285L;
-
- /**
- * The message provided when the exception was created.
- */
- private String detailMessage;
-
- /**
- * The cause of this Throwable. Null when there is no cause.
- */
- private Throwable cause = this;
-
- // BEGIN android-added
- /**
- * An intermediate representation of the stack trace. This field may
- * be accessed by the VM; do not rename.
- */
- private volatile Object stackState;
- // END android-added
-
- /**
- * A fully-expanded representation of the stack trace.
- */
- private StackTraceElement[] stackTrace;
-
- /**
- * Constructs a new {@code Throwable} that includes the current stack trace.
- */
- public Throwable() {
- super();
- fillInStackTrace();
- }
-
- /**
- * Constructs a new {@code Throwable} with the current stack trace and the
- * specified detail message.
- *
- * @param detailMessage
- * the detail message for this {@code Throwable}.
- */
- public Throwable(String detailMessage) {
- this();
- this.detailMessage = detailMessage;
- }
-
- /**
- * Constructs a new {@code Throwable} with the current stack trace, the
- * specified detail message and the specified cause.
- *
- * @param detailMessage
- * the detail message for this {@code Throwable}.
- * @param throwable
- * the cause of this {@code Throwable}.
- */
- public Throwable(String detailMessage, Throwable throwable) {
- this();
- this.detailMessage = detailMessage;
- cause = throwable;
- }
-
- /**
- * Constructs a new {@code Throwable} with the current stack trace and the
- * specified cause.
- *
- * @param throwable
- * the cause of this {@code Throwable}.
- */
- public Throwable(Throwable throwable) {
- this();
- this.detailMessage = throwable == null ? null : throwable.toString();
- cause = throwable;
- }
-
- // BEGIN android-changed
- /**
- * Records the stack trace from the point where this method has been called
- * to this {@code Throwable}. The method is public so that code which
- * catches a {@code Throwable} and then re-throws it can adjust the stack
- * trace to represent the location where the exception was re-thrown.
- *
- * @return this {@code Throwable} instance.
- */
- public Throwable fillInStackTrace() {
- // Fill in the intermediate representation
- stackState = nativeFillInStackTrace();
- // Mark the full representation as empty
- stackTrace = null;
- return this;
- }
- // END android-changed
-
- /**
- * Returns the extra information message which was provided when this
- * {@code Throwable} was created. Returns {@code null} if no message was
- * provided at creation time.
- *
- * @return this {@code Throwable}'s detail message.
- */
- public String getMessage() {
- return detailMessage;
- }
-
- /**
- * Returns the extra information message which was provided when this
- * {@code Throwable} was created. Returns {@code null} if no message was
- * provided at creation time. Subclasses may override this method to return
- * localized text for the message. Android returns the regular detail message.
- *
- * @return this {@code Throwable}'s localized detail message.
- */
- public String getLocalizedMessage() {
- return getMessage();
- }
-
- /**
- * Returns the array of stack trace elements of this {@code Throwable}. Each
- * {@code StackTraceElement} represents an entry in the call stack. The
- * element at position 0 is the top of the stack, that is, the stack frame
- * where this {@code Throwable} is thrown.
- *
- * @return a copy of the array of {@code StackTraceElement}s representing
- * the call stack. Changes in the array obtained from this call will
- * not change the call stack stored in this {@code Throwable}.
- * @see #printStackTrace()
- */
- public StackTraceElement[] getStackTrace() {
- return getInternalStackTrace().clone();
- }
-
- /**
- * Sets the array of stack trace elements. Each {@code StackTraceElement}
- * represents an entry in the call stack. A copy of the specified array is
- * stored in this {@code Throwable}. will be returned by {@code
- * getStackTrace()} and printed by {@code printStackTrace()}.
- *
- * @param trace
- * the new array of {@code StackTraceElement}s. A copy of the
- * array is stored in this {@code Throwable}, so subsequent
- * changes to {@code trace} will not change the call stack stored
- * in this {@code Throwable}.
- * @throws NullPointerException
- * if any element in {@code trace} is {@code null}.
- * @see #printStackTrace()
- */
- public void setStackTrace(StackTraceElement[] trace) {
- StackTraceElement[] newTrace = trace.clone();
- for (java.lang.StackTraceElement element : newTrace) {
- if (element == null) {
- throw new NullPointerException();
- }
- }
- stackTrace = newTrace;
- }
-
- /**
- * Writes a printable representation of this {@code Throwable}'s stack trace
- * to the {@code System.err} stream.
- *
- */
- public void printStackTrace() {
- printStackTrace(System.err);
- }
-
- /**
- * Counts the number of duplicate stack frames, starting from the
- * end of the stack.
- *
- * @param currentStack a stack to compare
- * @param parentStack a stack to compare
- *
- * @return the number of duplicate stack frames.
- */
- private static int countDuplicates(StackTraceElement[] currentStack,
- StackTraceElement[] parentStack) {
- int duplicates = 0;
- int parentIndex = parentStack.length;
- for (int i = currentStack.length; --i >= 0 && --parentIndex >= 0;) {
- StackTraceElement parentFrame = parentStack[parentIndex];
- if (parentFrame.equals(currentStack[i])) {
- duplicates++;
- } else {
- break;
- }
- }
- return duplicates;
- }
-
- /**
- * Returns an array of StackTraceElement. Each StackTraceElement
- * represents a entry on the stack.
- *
- * @return an array of StackTraceElement representing the stack
- */
- private StackTraceElement[] getInternalStackTrace() {
- if (stackTrace == null) {
- // BEGIN android-changed
- stackTrace = nativeGetStackTrace(stackState);
- stackState = null; // Clean up intermediate representation
- // END android-changed
- }
- return stackTrace;
- }
-
- /**
- * Writes a printable representation of this {@code Throwable}'s stack trace
- * to the specified print stream. If the {@code Throwable} contains a
- * {@link #getCause() cause}, the method will be invoked recursively for
- * the nested {@code Throwable}.
- *
- * @param err
- * the stream to write the stack trace on.
- */
- public void printStackTrace(PrintStream err) {
- err.println(toString());
- // Don't use getStackTrace() as it calls clone()
- // Get stackTrace, in case stackTrace is reassigned
- StackTraceElement[] stack = getInternalStackTrace();
- for (java.lang.StackTraceElement element : stack) {
- err.println("\tat " + element);
- }
-
- StackTraceElement[] parentStack = stack;
- Throwable throwable = getCause();
- while (throwable != null) {
- err.print("Caused by: ");
- err.println(throwable);
- StackTraceElement[] currentStack = throwable.getInternalStackTrace();
- int duplicates = countDuplicates(currentStack, parentStack);
- for (int i = 0; i < currentStack.length - duplicates; i++) {
- err.println("\tat " + currentStack[i]);
- }
- if (duplicates > 0) {
- err.println("\t... " + duplicates + " more");
- }
- parentStack = currentStack;
- throwable = throwable.getCause();
- }
- }
-
- /**
- * Writes a printable representation of this {@code Throwable}'s stack trace
- * to the specified print writer. If the {@code Throwable} contains a
- * {@link #getCause() cause}, the method will be invoked recursively for the
- * nested {@code Throwable}.
- *
- * @param err
- * the writer to write the stack trace on.
- */
- public void printStackTrace(PrintWriter err) {
- err.println(toString());
- // Don't use getStackTrace() as it calls clone()
- // Get stackTrace, in case stackTrace is reassigned
- StackTraceElement[] stack = getInternalStackTrace();
- for (java.lang.StackTraceElement element : stack) {
- err.println("\tat " + element);
- }
-
- StackTraceElement[] parentStack = stack;
- Throwable throwable = getCause();
- while (throwable != null) {
- err.print("Caused by: ");
- err.println(throwable);
- StackTraceElement[] currentStack = throwable.getInternalStackTrace();
- int duplicates = countDuplicates(currentStack, parentStack);
- for (int i = 0; i < currentStack.length - duplicates; i++) {
- err.println("\tat " + currentStack[i]);
- }
- if (duplicates > 0) {
- err.println("\t... " + duplicates + " more");
- }
- parentStack = currentStack;
- throwable = throwable.getCause();
- }
- }
-
- @Override
- public String toString() {
- String msg = getLocalizedMessage();
- String name = getClass().getName();
- if (msg == null) {
- return name;
- }
- return new StringBuffer(name.length() + 2 + msg.length()).append(name).append(": ")
- .append(msg).toString();
- }
-
- /**
- * Initializes the cause of this {@code Throwable}. The cause can only be
- * initialized once.
- *
- * @param throwable
- * the cause of this {@code Throwable}.
- * @return this {@code Throwable} instance.
- * @throws IllegalArgumentException
- * if {@code Throwable} is this object.
- * @throws IllegalStateException
- * if the cause has already been initialized.
- */
- public Throwable initCause(Throwable throwable) {
- // BEGIN android-note
- // removed synchronized modifier
- // END android-note
- if (cause == this) {
- if (throwable != this) {
- cause = throwable;
- return this;
- }
- throw new IllegalArgumentException("Cause cannot be the receiver");
- }
- throw new IllegalStateException("Cause already initialized");
- }
-
- /**
- * Returns the cause of this {@code Throwable}, or {@code null} if there is
- * no cause.
- *
- * @return Throwable this {@code Throwable}'s cause.
- */
- public Throwable getCause() {
- if (cause == this) {
- return null;
- }
- return cause;
- }
-
- private void writeObject(ObjectOutputStream s) throws IOException {
- // ensure the stackTrace field is initialized
- getInternalStackTrace();
- s.defaultWriteObject();
- }
-
- // BEGIN android-added
- /*
- * Creates a compact, VM-specific collection of goodies, suitable for
- * storing in the "stackState" field, based on the current thread's
- * call stack.
- */
- native private static Object nativeFillInStackTrace();
-
- /*
- * Creates an array of StackTraceElement objects from the data held
- * in "stackState".
- */
- native private static StackTraceElement[] nativeGetStackTrace(Object stackState);
- // END android-added
-}
diff --git a/luni-kernel/src/main/java/java/lang/ref/PhantomReference.java b/luni-kernel/src/main/java/java/lang/ref/PhantomReference.java
deleted file mode 100644
index 46ffcad..0000000
--- a/luni-kernel/src/main/java/java/lang/ref/PhantomReference.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang.ref;
-
-/**
- * Implements a phantom reference, which is the weakest of the three types of
- * references. Once the garbage collector decides that an object {@code obj} is
- * phantom-reachable, it is being enqueued
- * on the corresponding queue, but its referent is not cleared. That is, the
- * reference queue of the phantom reference must explicitly be processed by some
- * application code. As a consequence, a phantom reference that is not
- * registered with any reference queue does not make any sense.
- *
- * Phantom references are useful for implementing cleanup operations that are
- * necessary before an object gets garbage-collected. They are sometimes more
- * flexible than the {@link Object#finalize()} method.
- */
-public class PhantomReference
- * If the type of this field is a primitive type, the field value is
- * automatically wrapped.
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is null, a NullPointerException is thrown. If
- * the object is not an instance of the declaring class of the method, an
- * IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- *
- * @param object
- * the object to access
- * @return the field value, possibly wrapped
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public Object get(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getField(object, declaringClass, type, slot, flag);
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code
- * boolean}. This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public boolean getBoolean(Object object) throws IllegalAccessException,
- IllegalArgumentException {
- return getZField(object, declaringClass, type, slot, flag, TYPE_BOOLEAN);
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code byte}.
- * This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public byte getByte(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getBField(object, declaringClass, type, slot, flag, TYPE_BYTE);
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code char}.
- * This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public char getChar(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getCField(object, declaringClass, type, slot, flag, TYPE_CHAR);
- }
-
- /**
- * Returns the class that declares this field.
- *
- * @return the declaring class
- */
- public Class> getDeclaringClass() {
- return declaringClass;
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code
- * double}. This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public double getDouble(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getDField(object, declaringClass, type, slot, flag, TYPE_DOUBLE);
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code float}
- * . This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public float getFloat(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getFField(object, declaringClass, type, slot, flag, TYPE_FLOAT);
- }
-
- /**
- * Returns the value of the field in the specified object as an {@code int}.
- * This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public int getInt(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getIField(object, declaringClass, type, slot, flag, TYPE_INTEGER);
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code long}.
- * This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public long getLong(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getJField(object, declaringClass, type, slot, flag, TYPE_LONG);
- }
-
- /**
- * Returns the modifiers for this field. The {@link Modifier} class should
- * be used to decode the result.
- *
- * @return the modifiers for this field
- * @see Modifier
- */
- public int getModifiers() {
- return getFieldModifiers(declaringClass, slot);
- }
-
- private native int getFieldModifiers(Class> declaringClass, int slot);
-
- /**
- * Returns the name of this field.
- *
- * @return the name of this field
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns the value of the field in the specified object as a {@code short}
- * . This reproduces the effect of {@code object.fieldName}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * @param object
- * the object to access
- * @return the field value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public short getShort(Object object) throws IllegalAccessException, IllegalArgumentException {
- return getSField(object, declaringClass, type, slot, flag, TYPE_SHORT);
- }
-
- /**
- * Returns the constructor's signature in non-printable form. This is called
- * (only) from IO native code and needed for deriving the serialVersionUID
- * of the class
- *
- * @return the constructor's signature.
- */
- @SuppressWarnings("unused")
- private String getSignature() {
- return getSignature(type);
- }
-
- /**
- * Return the {@link Class} associated with the type of this field.
- *
- * @return the type of this field
- */
- public Class> getType() {
- return type;
- }
-
- /**
- * Returns an integer hash code for this field. Objects which are equal
- * return the same value for this method.
- *
- * The hash code for a Field is the exclusive-or combination of the hash
- * code of the field's name and the hash code of the name of its declaring
- * class.
- *
- * @return the hash code for this field
- * @see #equals
- */
- @Override
- public int hashCode() {
- // BEGIN android-changed
- return name.hashCode() ^ getDeclaringClass().getName().hashCode();
- // END android-changed
- }
-
- /**
- * Sets the value of the field in the specified object to the value. This
- * reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the field type is a primitive type, the value is automatically
- * unwrapped. If the unwrap fails, an IllegalArgumentException is thrown. If
- * the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void set(Object object, Object value) throws IllegalAccessException,
- IllegalArgumentException {
- setField(object, declaringClass, type, slot, flag, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code
- * boolean} value. This reproduces the effect of {@code object.fieldName =
- * value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setBoolean(Object object, boolean value) throws IllegalAccessException,
- IllegalArgumentException {
- setZField(object, declaringClass, type, slot, flag, TYPE_BOOLEAN, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code byte}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setByte(Object object, byte value) throws IllegalAccessException,
- IllegalArgumentException {
- setBField(object, declaringClass, type, slot, flag, TYPE_BYTE, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code char}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setChar(Object object, char value) throws IllegalAccessException,
- IllegalArgumentException {
- setCField(object, declaringClass, type, slot, flag, TYPE_CHAR, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code double}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setDouble(Object object, double value) throws IllegalAccessException,
- IllegalArgumentException {
- setDField(object, declaringClass, type, slot, flag, TYPE_DOUBLE, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code float}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setFloat(Object object, float value) throws IllegalAccessException,
- IllegalArgumentException {
- setFField(object, declaringClass, type, slot, flag, TYPE_FLOAT, value);
- }
-
- /**
- * Set the value of the field in the specified object to the {@code int}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setInt(Object object, int value) throws IllegalAccessException,
- IllegalArgumentException {
- setIField(object, declaringClass, type, slot, flag, TYPE_INTEGER, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code long}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setLong(Object object, long value) throws IllegalAccessException,
- IllegalArgumentException {
- setJField(object, declaringClass, type, slot, flag, TYPE_LONG, value);
- }
-
- /**
- * Sets the value of the field in the specified object to the {@code short}
- * value. This reproduces the effect of {@code object.fieldName = value}
- *
- * If this field is static, the object argument is ignored.
- * Otherwise, if the object is {@code null}, a NullPointerException is
- * thrown. If the object is not an instance of the declaring class of the
- * method, an IllegalArgumentException is thrown.
- *
- * If this Field object is enforcing access control (see AccessibleObject)
- * and this field is not accessible from the current context, an
- * IllegalAccessException is thrown.
- *
- * If the value cannot be converted to the field type via a widening
- * conversion, an IllegalArgumentException is thrown.
- *
- * @param object
- * the object to access
- * @param value
- * the new value
- * @throws NullPointerException
- * if the object is {@code null} and the field is non-static
- * @throws IllegalArgumentException
- * if the object is not compatible with the declaring class
- * @throws IllegalAccessException
- * if this field is not accessible
- */
- public void setShort(Object object, short value) throws IllegalAccessException,
- IllegalArgumentException {
- setSField(object, declaringClass, type, slot, flag, TYPE_SHORT, value);
- }
-
- /**
- * Returns a string containing a concise, human-readable description of this
- * field.
- *
- * The format of the string is:
- *
- * For example: {@code public static java.io.InputStream
- * java.lang.System.in}
- *
- * @return a printable representation for this field
- */
- @Override
- public String toString() {
- StringBuffer result = new StringBuffer(Modifier.toString(getModifiers()));
-
- if (result.length() != 0)
- result.append(' ');
- result.append(type.getName());
- result.append(' ');
- result.append(declaringClass.getName());
- result.append('.');
- result.append(name);
-
- return result.toString();
- }
-
- private native Object getField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck) throws IllegalAccessException;
-
- private native double getDField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native int getIField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native long getJField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native boolean getZField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native float getFField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native char getCField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native short getSField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native byte getBField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no) throws IllegalAccessException;
-
- private native void setField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, Object value) throws IllegalAccessException;
-
- private native void setDField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, double v) throws IllegalAccessException;
-
- private native void setIField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, int i) throws IllegalAccessException;
-
- private native void setJField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, long j) throws IllegalAccessException;
-
- private native void setZField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, boolean z) throws IllegalAccessException;
-
- private native void setFField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, float f) throws IllegalAccessException;
-
- private native void setCField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, char c) throws IllegalAccessException;
-
- private native void setSField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, short s) throws IllegalAccessException;
-
- private native void setBField(Object o, Class> declaringClass, Class> type, int slot,
- boolean noAccessCheck, int type_no, byte b) throws IllegalAccessException;
-
-}
diff --git a/luni-kernel/src/main/java/java/lang/reflect/Method.java b/luni-kernel/src/main/java/java/lang/reflect/Method.java
deleted file mode 100644
index 6678f8c..0000000
--- a/luni-kernel/src/main/java/java/lang/reflect/Method.java
+++ /dev/null
@@ -1,555 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang.reflect;
-
-import dalvik.system.VMStack;
-
-import java.lang.annotation.Annotation;
-
-import org.apache.harmony.kernel.vm.StringUtils;
-import org.apache.harmony.luni.lang.reflect.GenericSignatureParser;
-import org.apache.harmony.luni.lang.reflect.ListOfTypes;
-import org.apache.harmony.luni.lang.reflect.Types;
-
-/**
- * This class represents a method. Information about the method can be accessed,
- * and the method can be invoked dynamically.
- */
-public final class Method extends AccessibleObject implements GenericDeclaration, Member {
-
- private int slot;
-
- private Class> declaringClass;
-
- private String name;
-
- private Class>[] parameterTypes;
-
- private Class>[] exceptionTypes;
-
- private Class> returnType;
-
- private ListOfTypes genericExceptionTypes;
- private ListOfTypes genericParameterTypes;
- private Type genericReturnType;
- private TypeVariable See {@link java.util.concurrent.locks.LockSupport} for more
- * in-depth information of the behavior of this method. See {@link java.util.concurrent.locks.LockSupport} for more
- * in-depth information of the behavior of this method. See {@link java.util.concurrent.locks.LockSupport} for more
- * in-depth information of the behavior of this method.
- * Note that all methods in VM are static. There is no singleton instance which
- * represents the actively running VM.
- */
-public final class VM {
-
- /*
- * kernelVersion has the format: aabbxxyy where: aa - major version of
- * kernel. Must equal that stored in jcl. bb - minor version of kernel. Must
- * be >= that in jcl. xx - major version of jcl. Must equal that stored in
- * kernel. yy - minor version of jcl. Must be >= that in kernel.
- */
- private static final int kernelVersion = 0x01000100;
-
- /**
- * This method must be provided by the vm vendor, as it is used by
- * org.apache.harmony.kernel.vm.MsgHelp.setLocale() to get the bootstrap
- * ClassLoader. MsgHelp uses the bootstrap ClassLoader to find the resource
- * bundle of messages packaged with the bootstrap classes. Returns the
- * ClassLoader of the method (including natives) at the specified depth on
- * the stack of the calling thread. Frames representing the VM
- * implementation of java.lang.reflect are not included in the list. This is
- * not a public method as it can return the bootstrap class loader, which
- * should not be accessed by non-bootstrap classes. Notes:
- *
- * This method is for internal use only.
- *
- * @param targetClass Class the class to set the classpath of.
- * @see java.lang.Class
- */
- static int getCPIndexImpl(Class> targetClass) {
- return 0;
- }
-
- /**
- * Does internal initialization required by VM.
- *
- */
- static void initializeVM() {
- }
-
- /**
- * Registers a new virtual-machine shutdown hook. This is equivalent to the
- * 1.3 API of the same name.
- *
- * @param hook the hook (a Thread) to register
- */
- public static void addShutdownHook(Thread hook) {
- return;
- }
-
- /**
- * De-registers a previously-registered virtual-machine shutdown hook. This
- * is equivalent to the 1.3 API of the same name.
- *
- * @param hook the hook (a Thread) to de-register
- * @return true if the hook could be de-registered
- */
- public static boolean removeShutdownHook(Thread hook) {
- return false;
- }
-
- /**
- * This method must be provided by the vm vendor. Called to signal that the
- * org.apache.harmony.luni.internal.net.www.protocol.jar.JarURLConnection
- * class has been loaded and JarURLConnection.closeCachedFiles() should be
- * called on VM shutdown.
- */
- public static void closeJars() {
- return;
- }
-
- /**
- * This method must be provided by the vm vendor. Called to signal that the
- * org.apache.harmony.luni.util.DeleteOnExit class has been loaded and
- * DeleteOnExit.deleteOnExit() should be called on VM shutdown.
- */
- public static void deleteOnExit() {
- return;
- }
-
- // Constants used by getClassPathEntryType to indicate the class path entry
- // type
- static final int CPE_TYPE_UNKNOWN = 0;
-
- static final int CPE_TYPE_DIRECTORY = 1;
-
- static final int CPE_TYPE_JAR = 2;
-
- static final int CPE_TYPE_TCP = 3;
-
- static final int CPE_TYPE_UNUSABLE = 5;
-
- /**
- * Return the type of the specified entry on the class path for a
- * ClassLoader. Valid types are: CPE_TYPE_UNKNOWN CPE_TYPE_DIRECTORY
- * CPE_TYPE_JAR CPE_TYPE_TCP - this is obsolete CPE_TYPE_UNUSABLE
- *
- * @param classLoader the ClassLoader
- * @param cpIndex the index on the class path
- *
- * @return a int which specifies the class path entry type
- */
- static final int getClassPathEntryType(Object classLoader, int cpIndex) {
- return 0;
- }
-
- /**
- * Returns command line arguments passed to the VM. Internally these are
- * broken into optionString and extraInfo. This only returns the
- * optionString part.
- *
- *
- * @return a String array containing the optionString part of command line
- * arguments
- */
- public static String[] getVMArgs() {
- return null;
- }
-
- /**
- * Return the number of entries on the bootclasspath.
- *
- * @return an int which is the number of entries on the bootclasspath
- */
- static int getClassPathCount() {
- return 0;
- }
-
- /**
- * Return the specified bootclasspath entry.
- *
- * @param index the index of the bootclasspath entry
- *
- * @return a byte array containing the bootclasspath entry
- * specified in the vm options
- */
- static byte[] getPathFromClassPath(int index) {
- return null;
- }
-
- /**
- * This method must be provided by the vm vendor.
- *
- * Returns an int containing the version number of the kernel. Used to check for kernel
- * compatibility.
- *
- * @return an int containing the kernel version number
- */
- public static int getKernelVersion() {
- return kernelVersion;
- }
-
-}
diff --git a/luni-kernel/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java b/luni-kernel/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java
deleted file mode 100644
index a898f54..0000000
--- a/luni-kernel/src/main/java/org/apache/harmony/lang/annotation/AnnotationFactory.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.lang.annotation;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.Serializable;
-import java.lang.annotation.Annotation;
-import java.lang.annotation.IncompleteAnnotationException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.WeakHashMap;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-import static org.apache.harmony.lang.annotation.AnnotationMember.ARRAY;
-import static org.apache.harmony.lang.annotation.AnnotationMember.ERROR;
-
-/**
- * The annotation implementation based on dynamically generated proxy instances.
- * It conforms to all requirements stated in public APIs, see in particular
- * {@link java.lang.reflect.AnnotatedElement java.lang.reflect.AnnotatedElement}
- * and {@link java.lang.annotation.Annotation java.lang.annotation.Annotation}.
- * Namely, annotation instances are immutable and serializable; they provide
- * conforming access to annotation member values and required implementations of
- * methods declared in Annotation interface.
- *
- * @see android.lang.annotation.AnnotationMember
- * @see java.lang.annotation.Annotation
- *
- * @author Alexey V. Varlamov, Serguei S. Zapreyev
- * @version $Revision$
- */
-@SuppressWarnings({"serial"})
-public final class AnnotationFactory implements InvocationHandler, Serializable {
-
- private static final transient
- Map
+ * E.g. with strength == CollationAttribute.VALUE_SECONDARY, the tertiary difference
+ * is ignored
+ *
+ * E.g. with strength == PRIMARY, the secondary and tertiary difference are
+ * ignored.
+ * Example of use:
+ * Example of use:
+ *
+ * Note that you share these; you must not alter any of the fields, nor their array elements
+ * in the case of arrays. If you ever expose any of these things to user code, you must give
+ * them a clone rather than the original.
+ */
+public final class LocaleData {
+ // A cache for the locale-specific data.
+ private static final HashMap
+ * These represent an ordinary class or interface as found in the class
+ * hierarchy. The name associated with these {@code Class} instances is simply
+ * the fully qualified class name of the class or interface that it represents.
+ * In addition to this human-readable name, each class is also associated by a
+ * so-called signature, which is the letter "L", followed by the
+ * class name and a semicolon (";"). The signature is what the runtime system
+ * uses internally for identifying the class (for example in a DEX file).
+ *
+ * These represent the standard Java primitive types and hence share their
+ * names (for example "int" for the {@code int} primitive type). Although it is
+ * not possible to create new instances based on these {@code Class} instances,
+ * they are still useful for providing reflection information, and as the
+ * component type of array classes. There is one {@code Class} instance for each
+ * primitive type, and their signatures are:
+ *
+ *
+ * These represent the classes of Java arrays. There is one such {@code Class}
+ * instance per combination of array leaf component type and arity (number of
+ * dimensions). In this case, the name associated with the {@code Class}
+ * consists of one or more left square brackets (one per dimension in the array)
+ * followed by the signature of the class representing the leaf component type,
+ * which can be either an object type or a primitive type. The signature of a
+ * {@code Class} representing an array type is the same as its name. Examples
+ * of array class signatures are:
+ *
+ * If the class has not been loaded so far, it is being loaded and linked
+ * first. This is done through either the class loader of the calling class
+ * or one of its parent class loaders. The class is also being initialized,
+ * which means that a possible static initializer block is executed.
+ *
+ * @param className
+ * the name of the non-primitive-type class to find.
+ * @return the named {@code Class} instance.
+ * @throws ClassNotFoundException
+ * if the requested class can not be found.
+ * @throws LinkageError
+ * if an error occurs during linkage
+ * @throws ExceptionInInitializerError
+ * if an exception occurs during static initialization of a
+ * class.
+ */
+ public static Class> forName(String className) throws ClassNotFoundException {
+ return forName(className, true, VMStack.getCallingClassLoader());
+ }
+
+ /**
+ * Returns a {@code Class} object which represents the class with the
+ * specified name. The name should be the name of a class as described in
+ * the {@link Class class definition}, however {@code Class}es representing
+ * primitive types can not be found using this method. Security rules will
+ * be obeyed.
+ *
+ * If the class has not been loaded so far, it is being loaded and linked
+ * first. This is done through either the specified class loader or one of
+ * its parent class loaders. The caller can also request the class to be
+ * initialized, which means that a possible static initializer block is
+ * executed.
+ *
+ * @param className
+ * the name of the non-primitive-type class to find.
+ * @param initializeBoolean
+ * indicates whether the class should be initialized.
+ * @param classLoader
+ * the class loader to use to load the class.
+ * @return the named {@code Class} instance.
+ * @throws ClassNotFoundException
+ * if the requested class can not be found.
+ * @throws LinkageError
+ * if an error occurs during linkage
+ * @throws ExceptionInInitializerError
+ * if an exception occurs during static initialization of a
+ * class.
+ */
+ public static Class> forName(String className, boolean initializeBoolean,
+ ClassLoader classLoader) throws ClassNotFoundException {
+
+ if (classLoader == null) {
+ SecurityManager smgr = System.getSecurityManager();
+ if (smgr != null) {
+ ClassLoader calling = VMStack.getCallingClassLoader();
+ if (calling != null) {
+ smgr.checkPermission(new RuntimePermission("getClassLoader"));
+ }
+ }
+
+ classLoader = ClassLoader.getSystemClassLoader();
+ }
+ // Catch an Exception thrown by the underlying native code. It wraps
+ // up everything inside a ClassNotFoundException, even if e.g. an
+ // Error occurred during initialization. This as a workaround for
+ // an ExceptionInInitilaizerError that's also wrapped. It is actually
+ // expected to be thrown. Maybe the same goes for other errors.
+ // Not wrapping up all the errors will break android though.
+ Class> result;
+ try {
+ result = classForName(className, initializeBoolean,
+ classLoader);
+ } catch (ClassNotFoundException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof ExceptionInInitializerError) {
+ throw (ExceptionInInitializerError) cause;
+ }
+ throw e;
+ }
+ return result;
+ }
+
+ /*
+ * Returns a class by name without any security checks.
+ *
+ * @param className The name of the non-primitive type class to find
+ * @param initializeBoolean A boolean indicating whether the class should be
+ * initialized
+ * @param classLoader The class loader to use to load the class
+ * @return the named class.
+ * @throws ClassNotFoundException If the class could not be found
+ */
+ static native Class> classForName(String className, boolean initializeBoolean,
+ ClassLoader classLoader) throws ClassNotFoundException;
+
+ /**
+ * Returns an array containing {@code Class} objects for all public classes
+ * and interfaces that are members of this class. This includes public
+ * members inherited from super classes and interfaces. If there are no such
+ * class members or if this object represents a primitive type then an array
+ * of length 0 is returned.
+ *
+ * @return the public class members of the class represented by this object.
+ * @throws SecurityException
+ * if a security manager exists and it does not allow member
+ * access.
+ */
+ public Class[] getClasses() {
+ // BEGIN android-note
+ // trying to get closer to the RI which returns a raw class array.
+ // copied from newer version of harmony
+ // END android-note
+ checkPublicMemberAccess();
+ return getFullListOfClasses(true);
+ }
+
+ /**
+ * Returns the annotation of the given type. If there is no such annotation
+ * then the method returns {@code null}.
+ *
+ * @param annotationClass
+ * the annotation type.
+ * @return the annotation of the given type, or {@code null} if there is no
+ * such annotation.
+ */
+ @SuppressWarnings("unchecked")
+ public A getAnnotation(Class annotationClass) {
+ Annotation[] list = getAnnotations();
+ for (int i = 0; i < list.length; i++) {
+ if (annotationClass.isInstance(list[i])) {
+ return (A)list[i];
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns all the annotations of this class. If there are no annotations
+ * then an empty array is returned.
+ *
+ * @return a copy of the array containing this class' annotations.
+ * @see #getDeclaredAnnotations()
+ */
+ public Annotation[] getAnnotations() {
+ /*
+ * We need to get the annotations declared on this class, plus the
+ * annotations from superclasses that have the "@Inherited" annotation
+ * set. We create a temporary map to use while we accumulate the
+ * annotations and convert it to an array at the end.
+ *
+ * It's possible to have duplicates when annotations are inherited.
+ * We use a Map to filter those out.
+ *
+ * HashMap might be overkill here.
+ */
+ HashMap
+ * If there are no public fields or if this class represents an array class,
+ * a primitive type or {@code void} then an empty array is returned.
+ *
+ * If there are no public methods or if this {@code Class} represents a
+ * primitive type or {@code void} then an empty array is returned.
+ * Note: Because of the {@code getCallingClassLoader2()}
+ * check, this method must be called exactly one level deep into a
+ * public method on this instance. Note: Because of the {@code getCallingClassLoader2()}
+ * check, this method must be called exactly one level deep into a
+ * public method on this instance.
+ * Note: In order to conserve space in an embedded target like Android, we
+ * allow this method to return {@code null} for classes in the system
+ * protection domain (that is, for system classes). System classes are
+ * always given full permissions (that is, AllPermission). This can not be
+ * changed through the {@link java.security.Policy} class.
+ * Note: This method is implemented in native code, and,
+ * as such, is less efficient than using {@link ClassCache#REFLECT}
+ * to achieve the same goal. This method exists solely to help
+ * bootstrap the reflection bridge. Note: None of the methods perform access checks. It is up
+ * to the (package internal) clients of this code to perform such
+ * checks as necessary. Also Note: None of the returned array values are
+ * protected in any way. It is up to the (again, package internal)
+ * clients of this code to protect the arrays if they should ever
+ * escape the package.Class instances representing object types (classes or interfaces)
- * Classes representing primitive types
- *
- *
- * Classes representing array classes
- *
- *
- */
-public final class Class
If one of the doPrivileged methods is found, the walk terminate
- * and that frame is NOT included in the returned array. Notes:
- *
- *
- *
- *
- * @param maxDepth
- * maximum depth to walk the stack, -1 for the entire stack
- * @param stopAtPrivileged
- * stop at privileged classes
- * @return the array of the most recent classes on the stack
- */
- static final Class>[] getStackClasses(int maxDepth, boolean stopAtPrivileged) {
- return VMStack.getClasses(maxDepth, stopAtPrivileged);
- }
-
-}
diff --git a/luni-kernel/src/main/java/java/lang/ClassCache.java b/luni-kernel/src/main/java/java/lang/ClassCache.java
deleted file mode 100644
index 5ea6992..0000000
--- a/luni-kernel/src/main/java/java/lang/ClassCache.java
+++ /dev/null
@@ -1,702 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang;
-
-import org.apache.harmony.kernel.vm.LangAccess;
-import org.apache.harmony.kernel.vm.ReflectionAccess;
-
-import java.lang.reflect.AccessibleObject;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.EnumSet;
-import java.util.HashSet;
-
-/**
- * Cache of per-class data, meant to help the performance of reflection
- * methods.
- *
- * null
lists are considered equal. This is useful
- * for matching methods and constructors.
- *
- * null
- * if this instance's class doesn't have such a value (including
- * if this instance isn't in fact an enumeration)
- */
- @SuppressWarnings("unchecked")
- public T getEnumValue(String name) {
- Enum[] values = (Enum[]) getEnumValuesByName();
-
- if (values == null) {
- return null;
- }
-
- // Binary search.
-
- int min = 0;
- int max = values.length - 1;
-
- while (min <= max) {
- /*
- * The guessIdx calculation is equivalent to ((min + max)
- * / 2) but won't go wonky when min and max are close to
- * Integer.MAX_VALUE.
- */
- int guessIdx = min + ((max - min) >> 1);
- Enum guess = values[guessIdx];
- int cmp = name.compareTo(guess.name());
-
- if (cmp < 0) {
- max = guessIdx - 1;
- } else if (cmp > 0) {
- min = guessIdx + 1;
- } else {
- return (T) guess;
- }
- }
-
- return null;
- }
-
- /**
- * Gets the array of enumerated values, sorted by name.
- *
- * @return null-ok; the value array, or null
if this
- * instance's class isn't in fact an enumeration
- */
- public T[] getEnumValuesByName() {
- if (enumValuesByName == null) {
- T[] values = getEnumValuesInOrder();
-
- if (values != null) {
- values = (T[]) values.clone();
- Arrays.sort((Enum>[]) values, ENUM_COMPARATOR);
-
- /*
- * Note: It's only safe (concurrency-wise) to set the
- * instance variable after the array is properly sorted.
- */
- enumValuesByName = values;
- }
- }
-
- return enumValuesByName;
- }
-
- /**
- * Gets the array of enumerated values, in their original declared
- * order.
- *
- * @return null-ok; the value array, or null
if this
- * instance's class isn't in fact an enumeration
- */
- public T[] getEnumValuesInOrder() {
- if ((enumValuesInOrder == null) && clazz.isEnum()) {
- enumValuesInOrder = callEnumValues();
- }
-
- return enumValuesInOrder;
- }
-
- /**
- * Calls the static method values()
on this
- * instance's class, which is presumed to be a properly-formed
- * enumeration class, using proper privilege hygiene.
- *
- * @return non-null; the array of values as reported by
- * value()
- */
- @SuppressWarnings("unchecked")
- private T[] callEnumValues() {
- Method method;
-
- try {
- Method[] methods = getDeclaredPublicMethods();
- method = findMethodByName(methods, "values", (Class[]) null);
- method = REFLECT.accessibleClone(method);
- } catch (NoSuchMethodException ex) {
- // This shouldn't happen if the class is a well-formed enum.
- throw new UnsupportedOperationException(ex);
- }
-
- try {
- return (T[]) method.invoke((Object[]) null);
- } catch (IllegalAccessException ex) {
- // This shouldn't happen because the method is "accessible."
- throw new Error(ex);
- } catch (InvocationTargetException ex) {
- Throwable te = ex.getTargetException();
- if (te instanceof RuntimeException) {
- throw (RuntimeException) te;
- } else if (te instanceof Error) {
- throw (Error) te;
- } else {
- throw new Error(te);
- }
- }
- }
-
- /**
- * Gets the reflection access object. This uses reflection to do
- * so. My head is spinning.
- *
- * @return non-null; the reflection access object
- */
- private static ReflectionAccess getReflectionAccess() {
- /*
- * Note: We can't do AccessibleObject.class.getCache() to
- * get the cache, since that would cause a circularity in
- * initialization. So instead, we do a direct call into the
- * native side.
- */
- Method[] methods =
- Class.getDeclaredMethods(AccessibleObject.class, false);
-
- try {
- Method method = findMethodByName(methods, "getReflectionAccess",
- (Class[]) null);
- Class.setAccessibleNoCheck(method, true);
- return (ReflectionAccess) method.invoke((Object[]) null);
- } catch (NoSuchMethodException ex) {
- /*
- * This shouldn't happen because the method
- * AccessibleObject.getReflectionAccess() really is defined
- * in this module.
- */
- throw new Error(ex);
- } catch (IllegalAccessException ex) {
- // This shouldn't happen because the method is "accessible."
- throw new Error(ex);
- } catch (InvocationTargetException ex) {
- throw new Error(ex);
- }
- }
-
- /**
- * Comparator class for enumerated values. It compares strictly
- * by name.
- */
- private static class EnumComparator implements Comparator
- *
- *
- *
- * < user code > <- want this class
- * Class.getDeclared*();
- * Class.checkMemberAccess();
- * SecurityManager.checkMemberAccess(); <- current frame
- *
- *
- *
- *
- *
- * @param depth
- * the stack depth of the requested ClassLoader
- * @return the ClassLoader at the specified depth
- */
- static final ClassLoader getStackClassLoader(int depth) {
- Class>[] stack = VMStack.getClasses(depth + 1, false);
- if(stack.length < depth + 1) {
- return null;
- }
- return stack[depth].getClassLoader();
- }
-
- /**
- * This method must be provided by the VM vendor, as it is called by
- * java.lang.System.loadLibrary(). System.loadLibrary() cannot call
- * Runtime.loadLibrary() because this method loads the library using the
- * ClassLoader of the calling method. Loads and links the library specified
- * by the argument.
- *
- * @param libName
- * the name of the library to load
- * @param loader
- * the classloader in which to load the library
- * @throws UnsatisfiedLinkError
- * if the library could not be loaded
- * @throws SecurityException
- * if the library was not allowed to be loaded
- * java.lang
.
- */
-/*package*/ final class LangAccessImpl extends LangAccess {
- /** non-null; unique instance of this class */
- /*package*/ static final LangAccessImpl THE_ONE = new LangAccessImpl();
-
- /**
- * This class is not publicly instantiable. Use {@link #THE_ONE}.
- */
- private LangAccessImpl() {
- // This space intentionally left blank.
- }
-
- /** {@inheritDoc} */
- public
- * List
- *
- * @return this object's {@code Class} instance.
- */
- public final native Class extends Object> getClass();
-
- /**
- * Returns an integer hash code for this object. By contract, any two
- * objects for which {@code equals(Object)} returns {@code true} must return
- * the same hash code value. This means that subclasses of {@code Object}
- * usually override both methods or neither method.
- *
- * @return this object's hash code.
- * @see #equals
- */
- public native int hashCode();
-
- /**
- * Causes a thread which is waiting on this object's monitor (by means of
- * calling one of the {@code wait()} methods) to be woken up. If more than
- * one thread is waiting, one of them is chosen at the discretion of the
- * virtual machine. The chosen thread will not run immediately. The thread
- * that called {@code notify()} has to release the object's monitor first.
- * Also, the chosen thread still has to compete against other threads that
- * try to synchronize on the same object.
- *
- *
- *
- * @see #notifyAll
- * @see #wait()
- * @see #wait(long)
- * @see #wait(long,int)
- * @see java.lang.Thread
- */
- public final native void notify();
-
- /**
- * Causes all threads which are waiting on this object's monitor (by means
- * of calling one of the {@code wait()} methods) to be woken up. The threads
- * will not run immediately. The thread that called {@code notify()} has to
- * release the object's monitor first. Also, the threads still have to
- * compete against other threads that try to synchronize on the same object.
- *
- *
- *
- * @throws IllegalMonitorStateException
- * if the thread calling this method is not the owner of this
- * object's monitor.
- * @see #notify
- * @see #wait()
- * @see #wait(long)
- * @see #wait(long,int)
- * @see java.lang.Thread
- */
- public final native void notifyAll();
-
- /**
- * Returns a string containing a concise, human-readable description of this
- * object. Subclasses are encouraged to override this method and provide an
- * implementation that takes into account the object's type and data. The
- * default implementation simply concatenates the class name, the '@' sign
- * and a hexadecimal representation of the object's {@link #hashCode()},
- * that is, it is equivalent to the following expression:
- *
- *
- * getClass().getName() + '@' + Integer.toHexString(hashCode())
- *
- *
- * @return a printable representation of this object.
- */
- public String toString() {
- return getClass().getName() + '@' + Integer.toHexString(hashCode());
- }
-
- /**
- * Causes the calling thread to wait until another thread calls the {@code
- * notify()} or {@code notifyAll()} method of this object. This method can
- * only be invoked by a thread which owns this object's monitor; see
- * {@link #notify()} on how a thread can become the owner of a monitor.
- *
- *
- *
- * @param obj
- * the object to compare this instance with.
- * @return {@code true} if the specified object is equal to this
- * {@code StackTraceElement}; {@code false} otherwise.
- * @see #hashCode
- */
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof StackTraceElement)) {
- return false;
- }
- StackTraceElement castObj = (StackTraceElement) obj;
-
- /*
- * Unknown methods are never equal to anything (not strictly to spec,
- * but spec does not allow null method/class names)
- */
- if ((methodName == null) || (castObj.methodName == null)) {
- return false;
- }
-
- if (!getMethodName().equals(castObj.getMethodName())) {
- return false;
- }
- if (!getClassName().equals(castObj.getClassName())) {
- return false;
- }
- String localFileName = getFileName();
- if (localFileName == null) {
- if (castObj.getFileName() != null) {
- return false;
- }
- } else {
- if (!localFileName.equals(castObj.getFileName())) {
- return false;
- }
- }
- if (getLineNumber() != castObj.getLineNumber()) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Returns the fully qualified name of the class belonging to this
- * {@code StackTraceElement}.
- *
- * @return the fully qualified type name of the class
- */
- public String getClassName() {
- return (declaringClass == null) ? "
- * java.vendor.url
- * java.class.path
- * user.home
- * java.class.version
- * os.version
- * java.vendor
- * user.dir
- * user.timezone
- * path.separator
- * os.name
- * os.arch
- * line.separator
- * file.separator
- * user.name
- * java.version
- * java.home
- *
- *
- * @param prop
- * the name of the system property to look up.
- * @return the value of the specified system property or {@code null} if the
- * property doesn't exist.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertyAccess()} method does not allow the operation.
- */
- public static String getProperty(String prop) {
- return getProperty(prop, null);
- }
-
- /**
- * Returns the value of a particular system property. The {@code
- * defaultValue} will be returned if no such property has been found.
- *
- * @param prop
- * the name of the system property to look up.
- * @param defaultValue
- * the return value if the system property with the given name
- * does not exist.
- * @return the value of the specified system property or the {@code
- * defaultValue} if the property does not exist.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertyAccess()} method does not allow the operation.
- */
- public static String getProperty(String prop, String defaultValue) {
- if (prop.length() == 0) {
- throw new IllegalArgumentException();
- }
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPropertyAccess(prop);
- }
-
- return internalGetProperties().getProperty(prop, defaultValue);
- }
-
- /**
- * Sets the value of a particular system property.
- *
- * @param prop
- * the name of the system property to be changed.
- * @param value
- * the value to associate with the given property {@code prop}.
- * @return the old value of the property or {@code null} if the property
- * didn't exist.
- * @throws SecurityException
- * if a security manager exists and write access to the
- * specified property is not allowed.
- */
- public static String setProperty(String prop, String value) {
- if (prop.length() == 0) {
- throw new IllegalArgumentException();
- }
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new PropertyPermission(prop, "write"));
- }
- return (String)internalGetProperties().setProperty(prop, value);
- }
-
- /**
- * Removes a specific system property.
- *
- * @param key
- * the name of the system property to be removed.
- * @return the property value or {@code null} if the property didn't exist.
- * @throws NullPointerException
- * if the argument {@code key} is {@code null}.
- * @throws IllegalArgumentException
- * if the argument {@code key} is empty.
- * @throws SecurityException
- * if a security manager exists and write access to the
- * specified property is not allowed.
- */
- public static String clearProperty(String key) {
- if (key == null) {
- throw new NullPointerException();
- }
- if (key.length() == 0) {
- throw new IllegalArgumentException();
- }
-
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPermission(new PropertyPermission(key, "write"));
- }
- return (String)internalGetProperties().remove(key);
- }
-
- /**
- * Returns the {@link java.io.Console} associated with this VM, or null.
- * Not all VMs will have an associated console. A console is typically only
- * available for programs run from the command line.
- * @since 1.6
- * @hide
- */
- public static Console console() {
- return Console.getConsole();
- }
-
- /**
- * Returns null. Android does not use {@code SecurityManager}. This method
- * is only provided for source compatibility.
- *
- * @return null
- */
- public static SecurityManager getSecurityManager() {
- return null;
- }
-
- /**
- * Returns an integer hash code for the parameter. The hash code returned is
- * the same one that would be returned by the method {@code
- * java.lang.Object.hashCode()}, whether or not the object's class has
- * overridden hashCode(). The hash code for {@code null} is {@code 0}.
- *
- * @param anObject
- * the object to calculate the hash code.
- * @return the hash code for the given object.
- * @see java.lang.Object#hashCode
- */
- public static native int identityHashCode(Object anObject);
-
- /**
- * Loads the specified file as a dynamic library.
- *
- * @param pathName
- * the path of the file to be loaded.
- * @throws SecurityException
- * if the library was not allowed to be loaded.
- */
- public static void load(String pathName) {
- SecurityManager smngr = System.getSecurityManager();
- if (smngr != null) {
- smngr.checkLink(pathName);
- }
- Runtime.getRuntime().load(pathName, VMStack.getCallingClassLoader());
- }
-
- /**
- * Loads and links the shared library with the given name {@code libName}.
- * The file will be searched in the default directory for shared libraries
- * of the local system.
- *
- * @param libName
- * the name of the library to load.
- * @throws UnsatisfiedLinkError
- * if the library could not be loaded.
- * @throws SecurityException
- * if the library was not allowed to be loaded.
- */
- public static void loadLibrary(String libName) {
- SecurityManager smngr = System.getSecurityManager();
- if (smngr != null) {
- smngr.checkLink(libName);
- }
- Runtime.getRuntime().loadLibrary(libName, VMStack.getCallingClassLoader());
- }
-
- /**
- * Provides a hint to the virtual machine that it would be useful to attempt
- * to perform any outstanding object finalization.
- */
- public static void runFinalization() {
- Runtime.getRuntime().runFinalization();
- }
-
- /**
- * Ensures that, when the virtual machine is about to exit, all objects are
- * finalized. Note that all finalization which occurs when the system is
- * exiting is performed after all running threads have been terminated.
- *
- * @param flag
- * the flag determines if finalization on exit is enabled.
- * @deprecated this method is unsafe.
- */
- @SuppressWarnings("deprecation")
- @Deprecated
- public static void runFinalizersOnExit(boolean flag) {
- Runtime.runFinalizersOnExit(flag);
- }
-
- /**
- * Sets all system properties.
- *
- * @param p
- * the new system property.
- * @throws SecurityException
- * if a {@link SecurityManager} is installed and its {@code
- * checkPropertiesAccess()} method does not allow the operation.
- */
- public static void setProperties(Properties p) {
- SecurityManager secMgr = System.getSecurityManager();
- if (secMgr != null) {
- secMgr.checkPropertiesAccess();
- }
-
- systemProperties = p;
- }
-
- /**
- * Throws {@code UnsupportedOperationException}.
- *
- * run
will be
- * executed by the new {@code Thread}
- *
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- */
- public Thread(Runnable runnable) {
- create(null, runnable, null, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with a {@code Runnable} object and name
- * provided. The new {@code Thread} will belong to the same {@code
- * ThreadGroup} as the {@code Thread} calling this constructor.
- *
- * @param runnable
- * a {@code Runnable} whose method run
will be
- * executed by the new {@code Thread}
- * @param threadName
- * the name for the {@code Thread} being created
- *
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- */
- public Thread(Runnable runnable, String threadName) {
- if (threadName == null) {
- throw new NullPointerException();
- }
-
- create(null, runnable, threadName, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with no {@code Runnable} object and the
- * name provided. The new {@code Thread} will belong to the same {@code
- * ThreadGroup} as the {@code Thread} calling this constructor.
- *
- * @param threadName
- * the name for the {@code Thread} being created
- *
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- *
- */
- public Thread(String threadName) {
- if (threadName == null) {
- throw new NullPointerException();
- }
-
- create(null, null, threadName, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with a {@code Runnable} object and a
- * newly generated name. The new {@code Thread} will belong to the {@code
- * ThreadGroup} passed as parameter.
- *
- * @param group
- * {@code ThreadGroup} to which the new {@code Thread} will
- * belong
- * @param runnable
- * a {@code Runnable} whose method run
will be
- * executed by the new {@code Thread}
- * @throws SecurityException
- * if group.checkAccess()
fails with a
- * SecurityException
- * @throws IllegalThreadStateException
- * if group.destroy()
has already been done
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public Thread(ThreadGroup group, Runnable runnable) {
- create(group, runnable, null, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with a {@code Runnable} object, the given
- * name and belonging to the {@code ThreadGroup} passed as parameter.
- *
- * @param group
- * ThreadGroup to which the new {@code Thread} will belong
- * @param runnable
- * a {@code Runnable} whose method run
will be
- * executed by the new {@code Thread}
- * @param threadName
- * the name for the {@code Thread} being created
- * @throws SecurityException
- * if group.checkAccess()
fails with a
- * SecurityException
- * @throws IllegalThreadStateException
- * if group.destroy()
has already been done
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public Thread(ThreadGroup group, Runnable runnable, String threadName) {
- if (threadName == null) {
- throw new NullPointerException();
- }
-
- create(group, runnable, threadName, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with no {@code Runnable} object, the
- * given name and belonging to the {@code ThreadGroup} passed as parameter.
- *
- * @param group
- * {@code ThreadGroup} to which the new {@code Thread} will belong
- * @param threadName
- * the name for the {@code Thread} being created
- * @throws SecurityException
- * if group.checkAccess()
fails with a
- * SecurityException
- * @throws IllegalThreadStateException
- * if group.destroy()
has already been done
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public Thread(ThreadGroup group, String threadName) {
- if (threadName == null) {
- throw new NullPointerException();
- }
-
- create(group, null, threadName, 0);
- }
-
- /**
- * Constructs a new {@code Thread} with a {@code Runnable} object, the given
- * name and belonging to the {@code ThreadGroup} passed as parameter.
- *
- * @param group
- * {@code ThreadGroup} to which the new {@code Thread} will
- * belong
- * @param runnable
- * a {@code Runnable} whose method run
will be
- * executed by the new {@code Thread}
- * @param threadName
- * the name for the {@code Thread} being created
- * @param stackSize
- * a stack size for the new {@code Thread}. This has a highly
- * platform-dependent interpretation. It may even be ignored
- * completely.
- * @throws SecurityException
- * if group.checkAccess()
fails with a
- * SecurityException
- * @throws IllegalThreadStateException
- * if group.destroy()
has already been done
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public Thread(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
- if (threadName == null) {
- throw new NullPointerException();
- }
- create(group, runnable, threadName, stackSize);
- }
-
- /**
- * Package-scope method invoked by Dalvik VM to create "internal"
- * threads or attach threads created externally.
- *
- * Don't call Thread.currentThread(), since there may not be such
- * a thing (e.g. for Main).
- */
- Thread(ThreadGroup group, String name, int priority, boolean daemon) {
- synchronized (Thread.class) {
- id = ++Thread.count;
- }
-
- if (name == null) {
- this.name = "Thread-" + id;
- } else
- this.name = name;
-
- if (group == null) {
- throw new InternalError("group not specified");
- }
-
- this.group = group;
-
- this.target = null;
- this.stackSize = 0;
- this.priority = priority;
- this.daemon = daemon;
-
- /* add ourselves to our ThreadGroup of choice */
- this.group.addThread(this);
- }
-
- /**
- * Initializes a new, existing Thread object with a runnable object,
- * the given name and belonging to the ThreadGroup passed as parameter.
- * This is the method that the several public constructors delegate their
- * work to.
- *
- * @param group ThreadGroup to which the new Thread will belong
- * @param runnable a java.lang.Runnable whose method run
will
- * be executed by the new Thread
- * @param threadName Name for the Thread being created
- * @param stackSize Platform dependent stack size
- * @throws SecurityException if group.checkAccess()
fails
- * with a SecurityException
- * @throws IllegalThreadStateException if group.destroy()
has
- * already been done
- * @see java.lang.ThreadGroup
- * @see java.lang.Runnable
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
- SecurityManager smgr = System.getSecurityManager();
- if (smgr != null) {
- if (group == null) {
- group = smgr.getThreadGroup();
- }
-
- /*
- * Freaky security requirement: If the Thread's class is actually
- * a subclass of Thread and it tries to override either
- * getContextClassLoader() or setContextClassLoader(), the
- * SecurityManager has to allow this.
- */
- if (getClass() != Thread.class) {
- Class[] signature = new Class[] { ClassLoader.class };
-
- try {
- getClass().getDeclaredMethod("getContextClassLoader", signature);
- smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride"));
- } catch (NoSuchMethodException ex) {
- // Ignore. Just interested in the method's existence.
- }
-
- try {
- getClass().getDeclaredMethod("setContextClassLoader", signature);
- smgr.checkPermission(new RuntimePermission("enableContextClassLoaderOverride"));
- } catch (NoSuchMethodException ex) {
- // Ignore. Just interested in the method's existence.
- }
- }
- }
-
- Thread currentThread = Thread.currentThread();
- if (group == null) {
- group = currentThread.getThreadGroup();
- }
-
- group.checkAccess();
- if (group.isDestroyed()) {
- throw new IllegalThreadStateException("Group already destroyed");
- }
-
- this.group = group;
-
- synchronized (Thread.class) {
- id = ++Thread.count;
- }
-
- if (threadName == null) {
- this.name = "Thread-" + id;
- } else {
- this.name = threadName;
- }
-
- this.target = runnable;
- this.stackSize = stackSize;
-
- this.priority = currentThread.getPriority();
-
- this.contextClassLoader = currentThread.contextClassLoader;
-
- // Transfer over InheritableThreadLocals.
- if (currentThread.inheritableValues != null) {
- inheritableValues
- = new ThreadLocal.Values(currentThread.inheritableValues);
- }
-
- // store current AccessControlContext as inherited context for this thread
- SecurityUtils.putContext(this, AccessController.getContext());
-
- // add ourselves to our ThreadGroup of choice
- this.group.addThread(this);
- }
-
- /**
- * Returns the number of active {@code Thread}s in the running {@code
- * Thread}'s group and its subgroups.
- *
- * @return the number of {@code Thread}s
- */
- public static int activeCount() {
- return currentThread().getThreadGroup().activeCount();
- }
-
- /**
- * Is used for operations that require approval from a SecurityManager. If
- * there's none installed, this method is a no-op. If there's a
- * SecurityManager installed, {@link SecurityManager#checkAccess(Thread)} is
- * called for that SecurityManager.
- *
- * @throws SecurityException
- * if a SecurityManager is installed and it does not allow
- * access to the Thread.
- *
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public final void checkAccess() {
- // Forwards the message to the SecurityManager (if there's one) passing
- // the receiver as parameter
-
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkAccess(this);
- }
- }
-
- /**
- * Returns the number of stack frames in this thread.
- *
- * @return Number of stack frames
- * @deprecated The results of this call were never well defined. To make
- * things worse, it would depend on whether the Thread was
- * suspended or not, and suspend was deprecated too.
- */
- @Deprecated
- public int countStackFrames() {
- return getStackTrace().length;
- }
-
- /**
- * Returns the Thread of the caller, that is, the current Thread.
- *
- * @return the current Thread.
- */
- public static Thread currentThread() {
- return VMThread.currentThread();
- }
-
- /**
- * Destroys the receiver without any monitor cleanup.
- *
- * @deprecated Not implemented.
- */
- @Deprecated
- public void destroy() {
- throw new NoSuchMethodError("Thread.destroy()"); // TODO Externalize???
- }
-
- /**
- * Prints to the standard error stream a text representation of the current
- * stack for this Thread.
- *
- * @see Throwable#printStackTrace()
- */
- public static void dumpStack() {
- new Throwable("stack dump").printStackTrace();
- }
-
- /**
- * Copies an array with all Threads which are in the same ThreadGroup as the
- * receiver - and subgroups - into the array threads
passed as
- * parameter. If the array passed as parameter is too small no exception is
- * thrown - the extra elements are simply not copied.
- *
- * @param threads
- * array into which the Threads will be copied
- * @return How many Threads were copied over
- * @throws SecurityException
- * if the installed SecurityManager fails
- * {@link SecurityManager#checkAccess(Thread)}
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- */
- public static int enumerate(Thread[] threads) {
- Thread thread = Thread.currentThread();
- thread.checkAccess();
- return thread.getThreadGroup().enumerate(threads);
- }
-
- /**
- *
- *
- * are satisfied, a security check for
- * RuntimePermission("getClassLoader")
is performed first.
- *
- * @return ClassLoader The context ClassLoader
- * @see java.lang.ClassLoader
- * @see #getContextClassLoader()
- *
- * @throws SecurityException
- * if the aforementioned security check fails.
- */
- public ClassLoader getContextClassLoader() {
- // First, if the conditions
- // 1) there is a security manager
- // 2) the caller's class loader is not null
- // 3) the caller's class loader is not the same as the context
- // class loader and not an ancestor thereof
- // are satisfied we should perform a security check.
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- ClassLoader calling = VMStack.getCallingClassLoader();
-
- if (calling != null && !calling.isAncestorOf(contextClassLoader)) {
- sm.checkPermission(new RuntimePermission("getClassLoader"));
- }
- }
-
- return contextClassLoader;
- }
-
- /**
- * Returns the default exception handler that's executed when uncaught
- * exception terminates a thread.
- *
- * @return an {@link UncaughtExceptionHandler} or null
if
- * none exists.
- */
- public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
- return defaultUncaughtHandler;
- }
-
- /**
- * Returns the thread's identifier. The ID is a positive long
- * generated on thread creation, is unique to the thread, and doesn't change
- * during the lifetime of the thread; the ID may be reused after the thread
- * has been terminated.
- *
- * @return the thread's ID.
- */
- public long getId() {
- return id;
- }
-
- /**
- * Returns the name of the Thread.
- *
- * @return the Thread's name
- */
- public final String getName() {
- return name;
- }
-
- /**
- * Returns the priority of the Thread.
- *
- * @return the Thread's priority
- * @see Thread#setPriority
- */
- public final int getPriority() {
- return priority;
- }
-
- /**
- * Returns the a stack trace representing the current execution state of
- * this Thread.
- * RuntimePermission("getStackTrace")
is checked before
- * returning a result.
- * null
is returned.
- *
- * @return an {@link UncaughtExceptionHandler} instance or {@code null}.
- */
- public UncaughtExceptionHandler getUncaughtExceptionHandler() {
- if (uncaughtHandler != null)
- return uncaughtHandler;
- else
- return group; // ThreadGroup is instance of UEH
- }
-
- /**
- * Posts an interrupt request to this {@code Thread}. Unless the caller is
- * the {@link #currentThread()}, the method {@code checkAccess()} is called
- * for the installed {@code SecurityManager}, if any. This may result in a
- * {@code SecurityException} being thrown. The further behavior depends on
- * the state of this {@code Thread}:
- *
- *
- *
- * @throws SecurityException
- * if
checkAccess()
fails with a SecurityException
- * @see java.lang.SecurityException
- * @see java.lang.SecurityManager
- * @see Thread#interrupted
- * @see Thread#isInterrupted
- */
- public void interrupt() {
- checkAccess();
-
- if (interruptAction != null) {
- interruptAction.run();
- }
-
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- vmt.interrupt();
- }
- }
-
- /**
- * Returns a boolean
indicating whether the current Thread (
- * currentThread()
) has a pending interrupt request (
- * true
) or not (false
). It also has the side-effect of
- * clearing the flag.
- *
- * @return a boolean
indicating the interrupt status
- * @see Thread#currentThread
- * @see Thread#interrupt
- * @see Thread#isInterrupted
- */
- public static boolean interrupted() {
- return VMThread.interrupted();
- }
-
- /**
- * Returns true
if the receiver has already been started and
- * still runs code (hasn't died yet). Returns false
either if
- * the receiver hasn't been started yet or if it has already started and run
- * to completion and died.
- *
- * @return a boolean
indicating the liveness of the Thread
- * @see Thread#start
- */
- public final boolean isAlive() {
- return (vmThread != null);
- }
-
- /**
- * Returns a boolean
indicating whether the receiver is a
- * daemon Thread (true
) or not (false
) A
- * daemon Thread only runs as long as there are non-daemon Threads running.
- * When the last non-daemon Thread ends, the whole program ends no matter if
- * it had daemon Threads still running or not.
- *
- * @return a boolean
indicating whether the Thread is a daemon
- * @see Thread#setDaemon
- */
- public final boolean isDaemon() {
- return daemon;
- }
-
- /**
- * Returns a boolean
indicating whether the receiver has a
- * pending interrupt request (true
) or not (
- * false
)
- *
- * @return a boolean
indicating the interrupt status
- * @see Thread#interrupt
- * @see Thread#interrupted
- */
- public boolean isInterrupted() {
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- return vmt.isInterrupted();
- }
-
- return false;
- }
-
- /**
- * Blocks the current Thread (Thread.currentThread()
) until
- * the receiver finishes its execution and dies.
- *
- * @throws InterruptedException if interrupt()
was called for
- * the receiver while it was in the join()
call
- * @see Object#notifyAll
- * @see java.lang.ThreadDeath
- */
- public final void join() throws InterruptedException {
- VMThread t = vmThread;
- if (t == null) {
- return;
- }
-
- synchronized (t) {
- while (isAlive()) {
- t.wait();
- }
- }
- }
-
- /**
- * Blocks the current Thread (Thread.currentThread()
) until
- * the receiver finishes its execution and dies or the specified timeout
- * expires, whatever happens first.
- *
- * @param millis The maximum time to wait (in milliseconds).
- * @throws InterruptedException if interrupt()
was called for
- * the receiver while it was in the join()
call
- * @see Object#notifyAll
- * @see java.lang.ThreadDeath
- */
- public final void join(long millis) throws InterruptedException {
- join(millis, 0);
- }
-
- /**
- * Blocks the current Thread (Thread.currentThread()
) until
- * the receiver finishes its execution and dies or the specified timeout
- * expires, whatever happens first.
- *
- * @param millis The maximum time to wait (in milliseconds).
- * @param nanos Extra nanosecond precision
- * @throws InterruptedException if interrupt()
was called for
- * the receiver while it was in the join()
call
- * @see Object#notifyAll
- * @see java.lang.ThreadDeath
- */
- public final void join(long millis, int nanos) throws InterruptedException {
- if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) {
- throw new IllegalArgumentException();
- }
-
- // avoid overflow: if total > 292,277 years, just wait forever
- boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI;
- boolean forever = (millis | nanos) == 0;
- if (forever | overflow) {
- join();
- return;
- }
-
- VMThread t = vmThread;
- if (t == null) {
- return;
- }
-
- synchronized (t) {
- if (!isAlive()) {
- return;
- }
-
- // guaranteed not to overflow
- long nanosToWait = millis * NANOS_PER_MILLI + nanos;
-
- // wait until this thread completes or the timeout has elapsed
- long start = System.nanoTime();
- while (true) {
- t.wait(millis, nanos);
- if (!isAlive()) {
- break;
- }
- long nanosElapsed = System.nanoTime() - start;
- long nanosRemaining = nanosToWait - nanosElapsed;
- if (nanosRemaining <= 0) {
- break;
- }
- millis = nanosRemaining / NANOS_PER_MILLI;
- nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI);
- }
- }
- }
-
- /**
- * Resumes a suspended Thread. This is a no-op if the receiver was never
- * suspended, or suspended and already resumed. If the receiver is
- * suspended, however, makes it resume to the point where it was when it was
- * suspended.
- *
- * @throws SecurityException
- * if checkAccess()
fails with a SecurityException
- * @see Thread#suspend()
- * @deprecated Used with deprecated method {@link Thread#suspend}
- */
- @Deprecated
- public final void resume() {
- checkAccess();
-
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- vmt.resume();
- }
- }
-
- /**
- * Calls the run()
method of the Runnable object the receiver
- * holds. If no Runnable is set, does nothing.
- *
- * @see Thread#start
- */
- public void run() {
- if (target != null) {
- target.run();
- }
- }
-
- /**
- * Set the context ClassLoader for the receiver.
- * RuntimePermission("setContextClassLoader")
- * is checked prior to setting the handler.
- * checkAccess()
fails with a SecurityException
- * @see Thread#isDaemon
- */
- public final void setDaemon(boolean isDaemon) {
- checkAccess();
-
- if (hasBeenStarted) {
- throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
- }
-
- if (vmThread == null) {
- daemon = isDaemon;
- }
- }
-
- /**
- * RuntimePermission("setDefaultUncaughtExceptionHandler")
- * is checked prior to setting the handler.
- * null
.
- * @throws SecurityException
- * if the current SecurityManager fails the checkPermission
- * call.
- */
- public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkPermission(new RuntimePermission ("setDefaultUncaughtExceptionHandler"));
- }
-
- Thread.defaultUncaughtHandler = handler;
- }
-
- /**
- * Set the action to be executed when interruption, which is probably be
- * used to implement the interruptible channel. The action is null by
- * default. And if this method is invoked by passing in a non-null value,
- * this action's run() method will be invoked in interrupt()
.
- * checkAccess()
fails with a
- * SecurityException
- * @see Thread#getName
- */
- public final void setName(String threadName) {
- if (threadName == null) {
- throw new NullPointerException();
- }
-
- checkAccess();
-
- name = threadName;
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- /* notify the VM that the thread name has changed */
- vmt.nameChanged(threadName);
- }
- }
-
- /**
- * Sets the priority of the Thread. Note that the final priority set may not
- * be the parameter that was passed - it will depend on the receiver's
- * ThreadGroup. The priority cannot be set to be higher than the receiver's
- * ThreadGroup's maxPriority().
- *
- * @param priority
- * new priority for the Thread
- * @throws SecurityException
- * if checkAccess()
fails with a SecurityException
- * @throws IllegalArgumentException
- * if the new priority is greater than Thread.MAX_PRIORITY or
- * less than Thread.MIN_PRIORITY
- * @see Thread#getPriority
- */
- public final void setPriority(int priority) {
- checkAccess();
-
- if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
- throw new IllegalArgumentException("Priority out of range"); // TODO Externalize?
- }
-
- if (priority > group.getMaxPriority()) {
- priority = group.getMaxPriority();
- }
-
- this.priority = priority;
-
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- vmt.setPriority(priority);
- }
- }
-
- /**
- * null
.
- * @throws SecurityException
- * if the current SecurityManager fails the checkAccess call.
- */
- public void setUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
- checkAccess();
-
- uncaughtHandler = handler;
- }
-
- /**
- * Causes the thread which sent this message to sleep for the given interval
- * of time (given in milliseconds). The precision is not guaranteed - the
- * Thread may sleep more or less than requested.
- *
- * @param time
- * The time to sleep in milliseconds.
- * @throws InterruptedException
- * if interrupt()
was called for this Thread while
- * it was sleeping
- * @see Thread#interrupt()
- */
- public static void sleep(long time) throws InterruptedException {
- Thread.sleep(time, 0);
- }
-
- /**
- * Causes the thread which sent this message to sleep for the given interval
- * of time (given in milliseconds and nanoseconds). The precision is not
- * guaranteed - the Thread may sleep more or less than requested.
- *
- * @param millis
- * The time to sleep in milliseconds.
- * @param nanos
- * Extra nanosecond precision
- * @throws InterruptedException
- * if interrupt()
was called for this Thread while
- * it was sleeping
- * @see Thread#interrupt()
- */
- public static void sleep(long millis, int nanos) throws InterruptedException {
- VMThread.sleep(millis, nanos);
- }
-
- /**
- * Starts the new Thread of execution. The run()
method of
- * the receiver will be called by the receiver Thread itself (and not the
- * Thread calling start()
).
- *
- * @throws IllegalThreadStateException if the Thread has been started before
- *
- * @see Thread#run
- */
- public synchronized void start() {
- if (hasBeenStarted) {
- throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
- }
-
- hasBeenStarted = true;
-
- VMThread.create(this, stackSize);
- }
-
- /**
- * Requests the receiver Thread to stop and throw ThreadDeath. The Thread is
- * resumed if it was suspended and awakened if it was sleeping, so that it
- * can proceed to throw ThreadDeath.
- *
- * @throws SecurityException if checkAccess()
fails with a
- * SecurityException
- * @deprecated because stopping a thread in this manner is unsafe and can
- * leave your application and the VM in an unpredictable state.
- */
- @Deprecated
- public final void stop() {
- stop(new ThreadDeath());
- }
-
- /**
- * Requests the receiver Thread to stop and throw the
- * throwable()
. The Thread is resumed if it was suspended
- * and awakened if it was sleeping, so that it can proceed to throw the
- * throwable()
.
- *
- * @param throwable Throwable object to be thrown by the Thread
- * @throws SecurityException if checkAccess()
fails with a
- * SecurityException
- * @throws NullPointerException if throwable()
is
- * null
- * @deprecated because stopping a thread in this manner is unsafe and can
- * leave your application and the VM in an unpredictable state.
- */
- @Deprecated
- public final synchronized void stop(Throwable throwable) {
- SecurityManager securityManager = System.getSecurityManager();
- if (securityManager != null) {
- securityManager.checkAccess(this);
- if (Thread.currentThread() != this) {
- securityManager.checkPermission(new RuntimePermission("stopThread"));
- }
- }
-
- if (throwable == null) {
- throw new NullPointerException();
- }
-
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- vmt.stop(throwable);
- }
- }
-
- /**
- * Suspends this Thread. This is a no-op if the receiver is suspended. If
- * the receiver isAlive()
however, suspended it until
- * resume()
is sent to it. Suspend requests are not queued, which
- * means that N requests are equivalent to just one - only one resume
- * request is needed in this case.
- *
- * @throws SecurityException
- * if checkAccess()
fails with a SecurityException
- * @see Thread#resume()
- * @deprecated May cause deadlocks.
- */
- @Deprecated
- public final void suspend() {
- checkAccess();
-
- VMThread vmt = this.vmThread;
- if (vmt != null) {
- vmt.suspend();
- }
- }
-
- /**
- * Returns a string containing a concise, human-readable description of the
- * Thread. It includes the Thread's name, priority, and group name.
- *
- * @return a printable representation for the receiver.
- */
- @Override
- public String toString() {
- return "Thread[" + name + "," + priority + "," + group.getName() + "]";
- }
-
- /**
- * Causes the calling Thread to yield execution time to another Thread that
- * is ready to run. The actual scheduling is implementation-dependent.
- */
- public static void yield() {
- VMThread.yield();
- }
-
- /**
- * Indicates whether the current Thread has a monitor lock on the specified
- * object.
- *
- * @param object the object to test for the monitor lock
- * @return true if the current thread has a monitor lock on the specified
- * object; false otherwise
- */
- public static boolean holdsLock(Object object) {
- return currentThread().vmThread.holdsLock(object);
- }
-
- /**
- * Implemented by objects that want to handle cases where a thread is being
- * terminated by an uncaught exception. Upon such termination, the handler
- * is notified of the terminating thread and causal exception. If there is
- * no explicit handler set then the thread's group is the default handler.
- */
- public static interface UncaughtExceptionHandler {
- /**
- * The thread is being terminated by an uncaught exception. Further
- * exceptions thrown in this method are prevent the remainder of the
- * method from executing, but are otherwise ignored.
- *
- * @param thread the thread that has an uncaught exception
- * @param ex the exception that was thrown
- */
- void uncaughtException(Thread thread, Throwable ex);
- }
-
- /**
- * Implementation of unpark()
. See {@link LangAccessImpl}.
- */
- /*package*/ void unpark() {
- VMThread vmt = vmThread;
-
- if (vmt == null) {
- /*
- * vmThread is null before the thread is start()ed. In
- * this case, we just go ahead and set the state to
- * PREEMPTIVELY_UNPARKED. Since this happens before the
- * thread is started, we don't have to worry about
- * synchronizing with it.
- */
- parkState = ParkState.PREEMPTIVELY_UNPARKED;
- return;
- }
-
- synchronized (vmt) {
- switch (parkState) {
- case ParkState.PREEMPTIVELY_UNPARKED: {
- /*
- * Nothing to do in this case: By definition, a
- * preemptively unparked thread is to remain in
- * the preemptively unparked state if it is told
- * to unpark.
- */
- break;
- }
- case ParkState.UNPARKED: {
- parkState = ParkState.PREEMPTIVELY_UNPARKED;
- break;
- }
- default /*parked*/: {
- parkState = ParkState.UNPARKED;
- vmt.notifyAll();
- break;
- }
- }
- }
- }
-
- /**
- * Implementation of parkFor()
. See {@link LangAccessImpl}.
- * This method must only be called when this
is the current
- * thread.
- *
- * @param nanos number of nanoseconds to park for
- */
- /*package*/ void parkFor(long nanos) {
- VMThread vmt = vmThread;
-
- if (vmt == null) {
- // Running threads should always have an associated vmThread.
- throw new AssertionError();
- }
-
- synchronized (vmt) {
- switch (parkState) {
- case ParkState.PREEMPTIVELY_UNPARKED: {
- parkState = ParkState.UNPARKED;
- break;
- }
- case ParkState.UNPARKED: {
- long millis = nanos / NANOS_PER_MILLI;
- nanos %= NANOS_PER_MILLI;
-
- parkState = ParkState.PARKED;
- try {
- vmt.wait(millis, (int) nanos);
- } catch (InterruptedException ex) {
- interrupt();
- } finally {
- /*
- * Note: If parkState manages to become
- * PREEMPTIVELY_UNPARKED before hitting this
- * code, it should left in that state.
- */
- if (parkState == ParkState.PARKED) {
- parkState = ParkState.UNPARKED;
- }
- }
- break;
- }
- default /*parked*/: {
- throw new AssertionError(
- "shouldn't happen: attempt to repark");
- }
- }
- }
- }
-
- /**
- * Implementation of parkUntil()
. See {@link LangAccessImpl}.
- * This method must only be called when this
is the current
- * thread.
- *
- * @param time absolute milliseconds since the epoch to park until
- */
- /*package*/ void parkUntil(long time) {
- VMThread vmt = vmThread;
-
- if (vmt == null) {
- // Running threads should always have an associated vmThread.
- throw new AssertionError();
- }
-
- synchronized (vmt) {
- /*
- * Note: This conflates the two time bases of "wall clock"
- * time and "monotonic uptime" time. However, given that
- * the underlying system can only wait on monotonic time,
- * it is unclear if there is any way to avoid the
- * conflation. The downside here is that if, having
- * calculated the delay, the wall clock gets moved ahead,
- * this method may not return until well after the wall
- * clock has reached the originally designated time. The
- * reverse problem (the wall clock being turned back)
- * isn't a big deal, since this method is allowed to
- * spuriously return for any reason, and this situation
- * can safely be construed as just such a spurious return.
- */
- long delayMillis = time - System.currentTimeMillis();
-
- if (delayMillis <= 0) {
- parkState = ParkState.UNPARKED;
- } else {
- parkFor(delayMillis * NANOS_PER_MILLI);
- }
- }
- }
-}
diff --git a/luni-kernel/src/main/java/java/lang/ThreadGroup.java b/luni-kernel/src/main/java/java/lang/ThreadGroup.java
deleted file mode 100644
index 690fb45..0000000
--- a/luni-kernel/src/main/java/java/lang/ThreadGroup.java
+++ /dev/null
@@ -1,893 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang;
-
-/**
- * {@code ThreadGroup} is a means of organizing threads into a hierarchical structure.
- * This class is obsolete. See Effective Java Item 73, "Avoid thread groups" for details.
- * @see Thread
- * @see SecurityManager
- */
-public class ThreadGroup implements Thread.UncaughtExceptionHandler {
-
- // Name of this ThreadGroup
- private String name;
- // BEGIN android-note
- // VM needs this field name for debugging.
- // END android-note
-
- // Maximum priority for Threads inside this ThreadGroup
- private int maxPriority = Thread.MAX_PRIORITY;
-
- // The ThreadGroup to which this ThreadGroup belongs
- ThreadGroup parent;
- // BEGIN android-note
- // VM needs this field name for debugging.
- // END android-note
-
- int numThreads;
-
- // The Threads this ThreadGroup contains
- private Thread[] childrenThreads = new Thread[5];
-
- // The number of children groups
- int numGroups;
-
- // The ThreadGroups this ThreadGroup contains
- private ThreadGroup[] childrenGroups = new ThreadGroup[3];
-
- // Locked when using the childrenGroups field
- private class ChildrenGroupsLock {}
- private Object childrenGroupsLock = new ChildrenGroupsLock();
-
- // Locked when using the childrenThreads field
- private class ChildrenThreadsLock {}
- private Object childrenThreadsLock = new ChildrenThreadsLock();
-
- // Whether this ThreadGroup is a daemon ThreadGroup or not
- private boolean isDaemon;
-
- // Whether this ThreadGroup has already been destroyed or not
- private boolean isDestroyed;
-
- // BEGIN android-added
- /* the VM uses these directly; do not rename */
- static ThreadGroup mSystem = new ThreadGroup();
- static ThreadGroup mMain = new ThreadGroup(mSystem, "main");
- // END android-added
-
- // BEGIN android-removed
- // /**
- // * Used by the JVM to create the "system" ThreadGroup. Construct a
- // * ThreadGroup instance, and assign the name "system".
- // */
- // private ThreadGroup() {
- // name = "system";
- // }
- // END android-removed
-
- /**
- * Constructs a new {@code ThreadGroup} with the given name. The new {@code ThreadGroup}
- * will be child of the {@code ThreadGroup} to which the calling thread belongs.
- *
- * @param name the name
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
- * @see java.lang.Thread#currentThread
- */
-
- public ThreadGroup(String name) {
- this(Thread.currentThread().getThreadGroup(), name);
- }
-
- /**
- * Constructs a new {@code ThreadGroup} with the given name, as a child of the
- * given {@code ThreadGroup}.
- *
- * @param parent the parent
- * @param name the name
- * @throws NullPointerException if {@code parent == null}
- * @throws SecurityException if {@code checkAccess()} for the parent
- * group fails with a SecurityException
- * @throws IllegalThreadStateException if {@code parent} has been
- * destroyed already
- */
- public ThreadGroup(ThreadGroup parent, String name) {
- super();
- if (Thread.currentThread() != null) {
- // If parent is null we must throw NullPointerException, but that
- // will be done "for free" with the message send below
- parent.checkAccess();
- }
-
- this.name = name;
- this.setParent(parent);
- if (parent != null) {
- this.setMaxPriority(parent.getMaxPriority());
- if (parent.isDaemon()) {
- this.setDaemon(true);
- }
- }
- }
-
- /**
- * Initialize the special "system" ThreadGroup. Was "main" in Harmony,
- * but we have an additional group above that in Android.
- */
- ThreadGroup() {
- this.name = "system";
- this.setParent(null);
- }
-
- /**
- * Returns the number of running {@code Thread}s which are children of this thread group,
- * directly or indirectly.
- *
- * @return the number of children
- */
- public int activeCount() {
- // BEGIN android-changed
- int count = 0;
- // Lock the children thread list
- synchronized (this.childrenThreadsLock) {
- for (int i = 0; i < numThreads; i++) {
- if(childrenThreads[i].isAlive()) {
- count++;
- }
- }
- }
- // END android-changed
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- count += this.childrenGroups[i].activeCount();
- }
- }
- return count;
- }
-
- /**
- * Returns the number of {@code ThreadGroup}s which are children of this group,
- * directly or indirectly.
- *
- * @return the number of children
- */
- public int activeGroupCount() {
- int count = 0;
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenGroupsLock) {
- for (int i = 0; i < numGroups; i++) {
- // One for this group & the subgroups
- count += 1 + this.childrenGroups[i].activeGroupCount();
- }
- }
- return count;
- }
-
- /**
- * Adds a {@code Thread} to this thread group. This should only be visible to class
- * java.lang.Thread, and should only be called when a new Thread is created
- * and initialized by the constructor.
- *
- * @param thread Thread to add
- * @throws IllegalThreadStateException if this group has been destroyed already
- * @see #remove(java.lang.Thread)
- */
- final void add(Thread thread) throws IllegalThreadStateException {
- synchronized (this.childrenThreadsLock) {
- if (!isDestroyed) {
- if (childrenThreads.length == numThreads) {
- Thread[] newThreads = new Thread[childrenThreads.length * 2];
- System.arraycopy(childrenThreads, 0, newThreads, 0, numThreads);
- newThreads[numThreads++] = thread;
- childrenThreads = newThreads;
- } else {
- childrenThreads[numThreads++] = thread;
- }
- } else {
- throw new IllegalThreadStateException();
- }
- }
- }
-
- /**
- * Adds a {@code ThreadGroup} to this thread group.
- *
- * @param g ThreadGroup to add
- * @throws IllegalThreadStateException if this group has been destroyed already
- */
- private void add(ThreadGroup g) throws IllegalThreadStateException {
- synchronized (this.childrenGroupsLock) {
- if (!isDestroyed) {
- if (childrenGroups.length == numGroups) {
- ThreadGroup[] newGroups = new ThreadGroup[childrenGroups.length * 2];
- System.arraycopy(childrenGroups, 0, newGroups, 0, numGroups);
- newGroups[numGroups++] = g;
- childrenGroups = newGroups;
- } else {
- childrenGroups[numGroups++] = g;
- }
- } else {
- throw new IllegalThreadStateException();
- }
- }
- }
-
- /**
- * Does nothing. The definition of this method depends on the deprecated
- * method {@link #suspend()}. The exact behavior of this call was never
- * specified.
- *
- * @param b Used to control low memory implicit suspension
- * @return {@code true} (always)
- *
- * @deprecated Required deprecated method suspend().
- */
- @Deprecated
- public boolean allowThreadSuspension(boolean b) {
- // Does not apply to this VM, no-op
- return true;
- }
-
- /**
- * Checks the accessibility of this {@code ThreadGroup} from the perspective of the
- * caller. If there is a {@code SecurityManager} installed, calls
- * {@code checkAccess} with this thread group as a parameter, otherwise does
- * nothing.
- */
- public final void checkAccess() {
- SecurityManager currentManager = System.getSecurityManager();
- if (currentManager != null) {
- currentManager.checkAccess(this);
- }
- }
-
- /**
- * Destroys this thread group and recursively all its subgroups. It is only legal
- * to destroy a {@code ThreadGroup} that has no threads in it. Any daemon
- * {@code ThreadGroup} is destroyed automatically when it becomes empty (no threads
- * or thread groups in it).
- *
- * @throws IllegalThreadStateException if this thread group or any of its
- * subgroups has been destroyed already or if it still contains
- * threads.
- * @throws SecurityException if {@code this.checkAccess()} fails with
- * a SecurityException
- */
- public final void destroy() {
- checkAccess();
-
- // Lock this subpart of the tree as we walk
- synchronized (this.childrenThreadsLock) {
- synchronized (this.childrenGroupsLock) {
- // BEGIN android-added
- if (this.isDestroyed) {
- throw new IllegalThreadStateException(
- "Thread group was already destroyed: "
- + (this.name != null ? this.name : "n/a"));
- }
- if (this.numThreads > 0) {
- throw new IllegalThreadStateException(
- "Thread group still contains threads: "
- + (this.name != null ? this.name : "n/a"));
- }
- // END android-added
- int toDestroy = numGroups;
- // Call recursively for subgroups
- for (int i = 0; i < toDestroy; i++) {
- // We always get the first element - remember, when the
- // child dies it removes itself from our collection. See
- // below.
- this.childrenGroups[0].destroy();
- }
-
- if (parent != null) {
- parent.remove(this);
- }
-
- // Now that the ThreadGroup is really destroyed it can be tagged
- // as so
- this.isDestroyed = true;
- }
- }
- }
-
- /*
- * Auxiliary method that destroys this thread group and recursively all its
- * subgroups if this is a daemon ThreadGroup.
- *
- * @see #destroy
- * @see #setDaemon
- * @see #isDaemon
- */
- private void destroyIfEmptyDaemon() {
- // Has to be non-destroyed daemon to make sense
- synchronized (this.childrenThreadsLock) {
- if (isDaemon && !isDestroyed && numThreads == 0) {
- synchronized (this.childrenGroupsLock) {
- if (numGroups == 0) {
- destroy();
- }
- }
- }
- }
- }
-
- /**
- * Iterates over all active threads in this group (and its sub-groups) and
- * stores the threads in the given array. Returns when the array is full or
- * no more threads remain, whichever happens first.
- *
- *
- *
- *
- * The system may decide not to clear and enqueue soft references until a later
- * time, yet all {@code SoftReference}s pointing to softly reachable objects are
- * guaranteed to be cleared before the VM will throw an {@link
- * java.lang.OutOfMemoryError}.
- *
- * Soft references are useful for caches that should automatically have
- * their entries removed once they are not referenced any more (from outside),
- * and there is a need for memory. The difference between a {@code
- * SoftReference} and a {@code WeakReference} is the point of time at which the
- * decision is made to clear and enqueue the reference:
- *
- *
- *
- *
- *
- */
-public class SoftReference
- *
- *
- * Weak references are useful for mappings that should have their entries
- * removed automatically once they are not referenced any more (from outside).
- * The difference between a {@code SoftReference} and a {@code WeakReference} is
- * the point of time at which the decision is made to clear and enqueue the
- * reference:
- *
- *
- *
- *
- *
- */
-public class WeakReference
- *
- *
- * @param args
- * the arguments to the constructor
- *
- * @return the new, initialized, object
- *
- * @exception InstantiationException
- * if the class cannot be instantiated
- * @exception IllegalAccessException
- * if this constructor is not accessible
- * @exception IllegalArgumentException
- * if an incorrect number of arguments are passed, or an
- * argument could not be converted by a widening conversion
- * @exception InvocationTargetException
- * if an exception was thrown by the invoked constructor
- *
- * @see AccessibleObject
- */
- public T newInstance(Object... args) throws InstantiationException, IllegalAccessException,
- IllegalArgumentException, InvocationTargetException {
- return constructNative (args, declaringClass, parameterTypes, slot, flag);
- }
-
- private native T constructNative(Object[] args, Class
- *
- *
- *
- *
- * For example:
- * {@code public String(byte[],String) throws UnsupportedEncodingException}
- *
- * @return a printable representation for this constructor
- */
- @Override
- public String toString() {
- StringBuilder result = new StringBuilder(Modifier.toString(getModifiers()));
-
- if (result.length() != 0)
- result.append(' ');
- result.append(declaringClass.getName());
- result.append("(");
- result.append(toString(parameterTypes));
- result.append(")");
- if (exceptionTypes != null && exceptionTypes.length != 0) {
- result.append(" throws ");
- result.append(toString(exceptionTypes));
- }
-
- return result.toString();
- }
-}
diff --git a/luni-kernel/src/main/java/java/lang/reflect/Field.java b/luni-kernel/src/main/java/java/lang/reflect/Field.java
deleted file mode 100644
index baaafdd..0000000
--- a/luni-kernel/src/main/java/java/lang/reflect/Field.java
+++ /dev/null
@@ -1,907 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang.reflect;
-
-import dalvik.system.VMStack;
-
-import java.lang.annotation.Annotation;
-
-import org.apache.harmony.luni.lang.reflect.GenericSignatureParser;
-import org.apache.harmony.luni.lang.reflect.Types;
-import org.apache.harmony.kernel.vm.StringUtils;
-
-/**
- * This class represents a field. Information about the field can be accessed,
- * and the field's value can be accessed dynamically.
- */
-public final class Field extends AccessibleObject implements Member {
-
- private Class> declaringClass;
-
- private Class> type;
-
- private Type genericType;
-
- private volatile boolean genericTypesAreInitialized = false;
-
- private String name;
-
- private int slot;
-
- private static final int TYPE_BOOLEAN = 1;
-
- private static final int TYPE_BYTE = 2;
-
- private static final int TYPE_CHAR = 3;
-
- private static final int TYPE_SHORT = 4;
-
- private static final int TYPE_INTEGER = 5;
-
- private static final int TYPE_FLOAT = 6;
-
- private static final int TYPE_LONG = 7;
-
- private static final int TYPE_DOUBLE = 8;
-
- /**
- * Construct a clone of the given instance.
- *
- * @param orig non-null; the original instance to clone
- */
- /*package*/ Field(Field orig) {
- this(orig.declaringClass, orig.type, orig.name, orig.slot);
-
- // Copy the accessible flag.
- if (orig.flag) {
- this.flag = true;
- }
- }
-
- private Field(Class> declaringClass, Class> type, String name, int slot) {
- this.declaringClass = declaringClass;
- this.type = type;
- this.name = name;
- this.slot = slot;
- }
-
- private synchronized void initGenericType() {
- if (!genericTypesAreInitialized) {
- String signatureAttribute = getSignatureAttribute();
- GenericSignatureParser parser = new GenericSignatureParser(
- VMStack.getCallingClassLoader2());
- parser.parseForField(this.declaringClass, signatureAttribute);
- genericType = parser.fieldType;
- if (genericType == null) {
- genericType = getType();
- }
- genericTypesAreInitialized = true;
- }
- }
-
- /** {@inheritDoc} */
- @Override
- /* package */String getSignatureAttribute() {
- Object[] annotation = getSignatureAnnotation(declaringClass, slot);
-
- if (annotation == null) {
- return null;
- }
-
- return StringUtils.combineStrings(annotation);
- }
-
- /**
- * Get the Signature annotation for this field. Returns null if not found.
- */
- native private Object[] getSignatureAnnotation(Class declaringClass, int slot);
-
- /**
- * Indicates whether or not this field is synthetic.
- *
- * @return {@code true} if this field is synthetic, {@code false} otherwise
- */
- public boolean isSynthetic() {
- int flags = getFieldModifiers(declaringClass, slot);
- return (flags & Modifier.SYNTHETIC) != 0;
- }
-
- /**
- * Returns the string representation of this field, including the field's
- * generic type.
- *
- * @return the string representation of this field
- */
- public String toGenericString() {
- StringBuilder sb = new StringBuilder(80);
- // append modifiers if any
- int modifier = getModifiers();
- if (modifier != 0) {
- sb.append(Modifier.toString(modifier)).append(' ');
- }
- // append generic type
- appendGenericType(sb, getGenericType());
- sb.append(' ');
- // append full field name
- sb.append(getDeclaringClass().getName()).append('.').append(getName());
- return sb.toString();
- }
-
- /**
- * Indicates whether or not this field is an enumeration constant.
- *
- * @return {@code true} if this field is an enumeration constant, {@code
- * false} otherwise
- */
- public boolean isEnumConstant() {
- int flags = getFieldModifiers(declaringClass, slot);
- return (flags & Modifier.ENUM) != 0;
- }
-
- /**
- * Returns the generic type of this field.
- *
- * @return the generic type
- * @throws GenericSignatureFormatError
- * if the generic field signature is invalid
- * @throws TypeNotPresentException
- * if the generic type points to a missing type
- * @throws MalformedParameterizedTypeException
- * if the generic type points to a type that cannot be
- * instantiated for some reason
- */
- public Type getGenericType() {
- initGenericType();
- return Types.getType(genericType);
- }
-
- @Override
- public Annotation[] getDeclaredAnnotations() {
- return getDeclaredAnnotations(declaringClass, slot);
- }
-
- native private Annotation[] getDeclaredAnnotations(Class declaringClass, int slot);
-
- /**
- * Indicates whether or not the specified {@code object} is equal to this
- * field. To be equal, the specified object must be an instance of
- * {@code Field} with the same declaring class, type and name as this field.
- *
- * @param object
- * the object to compare
- * @return {@code true} if the specified object is equal to this method,
- * {@code false} otherwise
- * @see #hashCode
- */
- @Override
- public boolean equals(Object object) {
- return object instanceof Field && toString().equals(object.toString());
- }
-
- /**
- * Returns the value of the field in the specified object. This reproduces
- * the effect of {@code object.fieldName}
- *
- *
- *
- *
- *
- * @param receiver
- * the object on which to call this method
- * @param args
- * the arguments to the method
- *
- * @return the new, initialized, object
- *
- * @throws NullPointerException
- * if the receiver is null for a non-static method
- * @throws IllegalAccessException
- * if this method is not accessible
- * @throws IllegalArgumentException
- * if an incorrect number of arguments are passed, the receiver
- * is incompatible with the declaring class, or an argument
- * could not be converted by a widening conversion
- * @throws InvocationTargetException
- * if an exception was thrown by the invoked method
- *
- * @see AccessibleObject
- */
- public Object invoke(Object receiver, Object... args)
- throws IllegalAccessException, IllegalArgumentException,
- InvocationTargetException {
- if (args == null) {
- args = new Object[0];
- }
-
- return invokeNative (receiver, args, declaringClass, parameterTypes, returnType, slot, flag);
- }
-
- private native Object invokeNative(Object obj, Object[] args, Class> declaringClass, Class>[] parameterTypes, Class> returnType, int slot, boolean noAccessCheck)
- throws IllegalAccessException,
- IllegalArgumentException,
- InvocationTargetException;
-
- /**
- * Returns a string containing a concise, human-readable description of this
- * method. The format of the string is:
- *
- *
- *
- *
- *
- *
- * For example: {@code public native Object
- * java.lang.Method.invoke(Object,Object) throws
- * IllegalAccessException,IllegalArgumentException
- * ,InvocationTargetException}
- *
- * @return a printable representation for this method
- */
- @Override
- public String toString() {
- StringBuilder result = new StringBuilder(Modifier.toString(getModifiers()));
-
- if (result.length() != 0)
- result.append(' ');
- result.append(returnType.getName());
- result.append(' ');
- result.append(declaringClass.getName());
- result.append('.');
- result.append(name);
- result.append("(");
- result.append(toString(parameterTypes));
- result.append(")");
- if (exceptionTypes != null && exceptionTypes.length != 0) {
- result.append(" throws ");
- result.append(toString(exceptionTypes));
- }
-
- return result.toString();
- }
-
- /**
- * Returns the constructor's signature in non-printable form. This is called
- * (only) from IO native code and needed for deriving the serialVersionUID
- * of the class
- *
- * @return The constructor's signature.
- */
- @SuppressWarnings("unused")
- private String getSignature() {
- StringBuilder result = new StringBuilder();
-
- result.append('(');
- for(int i = 0; i < parameterTypes.length; i++) {
- result.append(getSignature(parameterTypes[i]));
- }
- result.append(')');
- result.append(getSignature(returnType));
-
- return result.toString();
- }
-
-}
diff --git a/luni-kernel/src/main/java/java/lang/reflect/ReflectionAccessImpl.java b/luni-kernel/src/main/java/java/lang/reflect/ReflectionAccessImpl.java
deleted file mode 100644
index 15cd798..0000000
--- a/luni-kernel/src/main/java/java/lang/reflect/ReflectionAccessImpl.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package java.lang.reflect;
-
-import org.apache.harmony.kernel.vm.ReflectionAccess;
-
-/**
- * Implementation of bridge from {@code java.lang} to
- * {@code java.lang.reflect}.
- */
-/*package*/ final class ReflectionAccessImpl implements ReflectionAccess {
- /** non-null; unique instance of this class */
- /*package*/ static final ReflectionAccessImpl THE_ONE =
- new ReflectionAccessImpl();
-
- /**
- * This class is not publicly instantiable. Use {@link #THE_ONE}.
- */
- private ReflectionAccessImpl() {
- // This space intentionally left blank.
- }
-
- public Method clone(Method method) {
- return new Method(method);
- }
-
- public Field clone(Field field) {
- return new Field(field);
- }
-
- public Method accessibleClone(Method method) {
- Method result = new Method(method);
- result.setAccessibleNoCheck(true);
- return result;
- }
-
- public void setAccessibleNoCheck(AccessibleObject ao, boolean accessible) {
- ao.setAccessibleNoCheck(accessible);
- }
-}
diff --git a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/LangAccess.java b/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/LangAccess.java
deleted file mode 100644
index 8b321e4..0000000
--- a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/LangAccess.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.kernel.vm;
-
-import dalvik.system.VMStack;
-
-/**
- * Bridge into java.lang
from other trusted parts of the
- * core library. Trusted packages either get seeded with an instance
- * of this class directly or may call {@link #getInstance} on this
- * class, to allow them to call into what would otherwise be
- * package-scope functionality in java.lang
.
- */
-public abstract class LangAccess {
- /** unique instance of this class */
- private static LangAccess theInstance = null;
-
- /**
- * Sets the unique instance of this class. This may only be done once.
- *
- * @param instance non-null; the instance
- */
- public static void setInstance(LangAccess instance) {
- if (theInstance != null) {
- throw new UnsupportedOperationException("already initialized");
- }
-
- theInstance = instance;
- }
-
- /**
- * Gets the unique instance of this class. This is only allowed in
- * very limited situations.
- */
- public static LangAccess getInstance() {
- /*
- * Only code on the bootclasspath is allowed to get at the
- * instance.
- */
- ClassLoader calling = VMStack.getCallingClassLoader2();
- ClassLoader current = LangAccess.class.getClassLoader();
-
- if ((calling != null) && (calling != current)) {
- throw new SecurityException("LangAccess access denied");
- }
-
- if (theInstance == null) {
- throw new UnsupportedOperationException("not yet initialized");
- }
-
- return theInstance;
- }
-
- /**
- * Gets a shared array of the enum constants of a given class in
- * declaration (ordinal) order. It is not safe to hand out this
- * array to any user code.
- *
- * @param clazz non-null; the class in question
- * @return null-ok; the class's list of enumerated constants in
- * declaration order or null
if the given class is
- * not an enumeration
- */
- public abstract 0
- * to park indefinitely
- * @throws IllegalArgumentException thrown if nanos < 0
- */
- public abstract void parkFor(long nanos);
-
- /**
- * Parks the current thread until the specified system time. This
- * method attempts to unpark the current thread immediately after
- * System.currentTimeMillis()
reaches the specified
- * value, if no other thread unparks it first. If the thread has
- * been "preemptively unparked," this method cancels that
- * unparking and returns immediately. This method may also return
- * spuriously (that is, without the thread being told to unpark
- * and without the indicated amount of time elapsing).
- *
- * java.lang
to java.lang.reflect
.
- * The package java.lang
gets seeded with an instance of
- * this interface, to allow it to call into what would otherwise be
- * package-scope functionality in java.lang.reflect
.
- */
-public interface ReflectionAccess {
- /**
- * Gets a clone of the given method.
- *
- * @param method non-null; the method to clone
- * @return non-null; the clone
- */
- public Method clone(Method method);
-
- /**
- * Gets a clone of the given field.
- *
- * @param field non-null; the field to clone
- * @return non-null; the clone
- */
- public Field clone(Field field);
-
- /**
- * Gets a clone of the given method, where the clone has
- * its "accessible" flag set to true
- *
- * @param method non-null; the method to clone
- * @return non-null; the accessible clone
- */
- public Method accessibleClone(Method method);
-
- /**
- * Sets the accessible flag on a given {@link AccessibleObject}
- * without doing any checks.
- *
- * @param ao non-null; the instance in question
- * @param flag the new value for the accessible flag
- */
- public void setAccessibleNoCheck(AccessibleObject ao, boolean flag);
-}
diff --git a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/StringUtils.java b/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/StringUtils.java
deleted file mode 100644
index b392388..0000000
--- a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/StringUtils.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.kernel.vm;
-
-/**
- * String utility functions.
- */
-public final class StringUtils {
- /**
- * This class is uninstantiable.
- */
- private StringUtils() {
- // This space intentionally left blank.
- }
-
- /**
- * Combine a list of strings in an Object[]
into a single
- * string.
- *
- * @param list non-null; the strings to combine
- * @return non-null; the combined form
- */
- public static String combineStrings(Object[] list) {
- int listLength = list.length;
-
- switch (listLength) {
- case 0: {
- return "";
- }
- case 1: {
- return (String) list[0];
- }
- }
-
- int strLength = 0;
-
- for (int i = 0; i < listLength; i++) {
- strLength += ((String) list[i]).length();
- }
-
- StringBuilder sb = new StringBuilder(strLength);
-
- for (int i = 0; i < listLength; i++) {
- sb.append(list[i]);
- }
-
- return sb.toString();
- }
-}
diff --git a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/VM.java b/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/VM.java
deleted file mode 100644
index 8aa7c4b..0000000
--- a/luni-kernel/src/main/java/org/apache/harmony/kernel/vm/VM.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.kernel.vm;
-
-/**
- * This class must be implemented by the vm vendor. Represents the running
- * virtual machine. All VM specific API are implemented on this class.
- *
- *
- *
- * @param depth the stack depth of the requested ClassLoader
- * @return the ClassLoader at the specified depth
- * @see java.lang.ClassLoader#getStackClassLoader
- */
- static final ClassLoader getStackClassLoader(int depth) {
- return null;
- };
-
- /**
- * This method must be provided by the vm vendor, as it is used by other
- * provided class implementations. For example,
- * java.io.ObjectInputStream.readObject() and
- * java.io.ObjectInputStream.resolveProxyClass(). It is also useful for
- * other classes, such as java.rmi.server.RMIClassLoader. Walk the stack and
- * answer the most recent non-null and non-bootstrap ClassLoader on the
- * stack of the calling thread. If no such ClassLoader is found, null is
- * returned. Notes: 1) This method operates on the defining classes of
- * methods on stack. NOT the classes of receivers.
- *
- * @return the first non-bootstrap ClassLoader on the stack
- */
- static public final ClassLoader getNonBootstrapClassLoader() {
- return null;
- };
-
- /**
- * Initialize the classloader.
- *
- * @param loader ClassLoader the ClassLoader instance
- * @param bootLoader boolean true for the bootstrap class loader
- */
- public final static void initializeClassLoader(ClassLoader loader, boolean bootLoader) {
- return;
- };
-
- /**
- * This method must be provided by the vm vendor.
- *
- * Searches an internal table of strings for a string equal to the specified
- * String. If the string is not in the table, it is added. Returns the
- * string contained in the table which is equal to the specified String. The
- * same string object is always answered for strings which are equal.
- *
- * @param string the String to intern
- *
- * @return the interned string equal to the specified String
- */
- public static final String intern(String string) {
- return null;
- }
-
- /**
- * Native used to find and load a class using the VM
- *
- * @return java.lang.Class the class or null.
- * @param className String the name of the class to search for.
- * @param classLoader the classloader to do the work
- */
- static Class> findClassOrNull(String className, ClassLoader classLoader) {
- return null;
- }
-
- /**
- * This method must be included, as it is used by
- * ResourceBundle.getBundle(), and other places as well. The reference
- * implementation of this method uses the getStackClassLoader() method.
- * Returns the ClassLoader of the method that called the caller. i.e. A.x()
- * calls B.y() calls callerClassLoader(), A's ClassLoader will be returned.
- * Returns null for the bootstrap ClassLoader.
- *
- * @return a ClassLoader or null for the bootstrap ClassLoader
- * @throws SecurityException when called from a non-bootstrap Class
- */
- public static ClassLoader callerClassLoader() {
- return null;
- }
-
- /**
- * This method must be provided by the vm vendor, as it is used by
- * org.apache.harmony.luni.util.MsgHelp.setLocale() to get the bootstrap
- * ClassLoader. MsgHelp uses the bootstrap ClassLoader to find the resource
- * bundle of messages packaged with the bootstrap classes. The reference
- * implementation of this method uses the getStackClassLoader() method.
- *
- * Returns the ClassLoader of the method that called the caller. i.e. A.x()
- * calls B.y() calls callerClassLoader(), A's ClassLoader will be returned.
- * Returns null for the bootstrap ClassLoader.
- *
- * @return a ClassLoader
- *
- * @throws SecurityException when called from a non-bootstrap Class
- */
- public static ClassLoader bootCallerClassLoader() {
- return null;
- }
-
- /**
- * Native used to dump a string to the system console for debugging.
- *
- * @param str String the String to display
- */
- public static void dumpString(String str) {
- return;
- }
-
- /**
- * Get the classpath entry that was used to load the class that is the arg.
- *
Note, actual underlying implementation mechanism does not matter - it may
- * differ completely from this class.
- * @return true if the passed object is equivalent annotation instance,
- * false otherwise.
- * @see android.lang.annotation.AnnotationMember#equals(Object)
- */
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!klazz.isInstance(obj)) {
- return false;
- }
- Object handler = null;
- if (Proxy.isProxyClass(obj.getClass())
- && (handler = Proxy.getInvocationHandler(obj)) instanceof AnnotationFactory ) {
- AnnotationFactory other = (AnnotationFactory) handler;
- if (elements.length != other.elements.length) {
- return false;
- }
- next: for (AnnotationMember el1 : elements){
- for (AnnotationMember el2 : other.elements) {
- if (el1.equals(el2)) {
- continue next;
- }
- }
- return false;
- }
- return true;
- } else {
- // encountered foreign annotation implementaton
- // so have to obtain element values via invocation
- // of corresponding methods
- for (final AnnotationMember el : elements) {
- if (el.tag == ERROR) {
- // undefined value is incomparable (transcendent)
- return false;
- }
- try {
- if (!el.definingMethod.isAccessible()) {
- AccessController.doPrivileged(new PrivilegedAction
+ *
+ * Collator myCollation = Collator.createInstance(Locale::US);
+ * myCollation.setStrength(PRIMARY);
+ * // result will be "abc" == "ABC"
+ * // tertiary differences will be ignored
+ * int result = myCollation->compare("abc", "ABC");
+ *
+ * @param strength the new comparison level.
+ * @exception IllegalArgumentException when argument does not belong to any collation strength
+ * mode or error occurs while setting data.
+ * @see #PRIMARY
+ * @see #SECONDARY
+ * @see #TERTIARY
+ * @see #QUATERNARY
+ * @see #IDENTICAL
+ * @stable ICU 2.4
+ */
+ public void setStrength(int strength) {
+ NativeCollation.setAttribute(m_collator_, CollationAttribute.STRENGTH, strength);
+ }
+
+ /**
+ * Sets the attribute to be used in comparison or transformation.
+ *
+ *
+ * Collator myCollation = Collator.createInstance(Locale::US);
+ * myCollation.setAttribute(CollationAttribute.CASE_LEVEL,
+ * CollationAttribute.VALUE_ON);
+ * int result = myCollation->compare("\\u30C3\\u30CF",
+ * "\\u30C4\\u30CF");
+ * // result will be -1
+ *
+ * @param type the attribute to be set from CollationAttribute
+ * @param value attribute value from CollationAttribute
+ * @stable ICU 2.4
+ */
+ public void setAttribute(int type, int value) {
+ NativeCollation.setAttribute(m_collator_, type, value);
+ }
+
+ /**
+ * Gets the attribute to be used in comparison or transformation.
+ * @param type the attribute to be set from CollationAttribute
+ * @return value attribute value from CollationAttribute
+ * @stable ICU 2.4
+ */
+ public int getAttribute(int type) {
+ return NativeCollation.getAttribute(m_collator_, type);
+ }
+
+ public CollationKey getCollationKey(String source) {
+ if (source == null) {
+ return null;
+ }
+ byte[] key = NativeCollation.getSortKey(m_collator_, source);
+ if (key == null) {
+ return null;
+ }
+ return new CollationKey(source, key);
+ }
+
+ /**
+ * Get the collation rules of this Collation object
+ * The rules will follow the rule syntax.
+ * @return collation rules.
+ * @stable ICU 2.4
+ */
+ public String getRules() {
+ return NativeCollation.getRules(m_collator_);
+ }
+
+ /**
+ * Create a CollationElementIterator object that will iterator over the
+ * elements in a string, using the collation rules defined in this
+ * RuleBasedCollator
+ * @param source string to iterate over
+ * @return address of C collationelement
+ * @exception IllegalArgumentException thrown when error occurs
+ * @stable ICU 2.4
+ */
+ public CollationElementIterator getCollationElementIterator(String source) {
+ CollationElementIterator result = new CollationElementIterator(
+ NativeCollation.getCollationElementIterator(m_collator_, source));
+ // result.setOwnCollationElementIterator(true);
+ return result;
+ }
+
+ public CollationElementIterator getCollationElementIterator(CharacterIterator it) {
+ // We only implement the String-based API, so build a string from the iterator.
+ return getCollationElementIterator(characterIteratorToString(it));
+ }
+
+ private String characterIteratorToString(CharacterIterator it) {
+ StringBuilder result = new StringBuilder();
+ for (char ch = it.current(); ch != CharacterIterator.DONE; ch = it.next()) {
+ result.append(ch);
+ }
+ return result.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return 42; // No-one uses RuleBasedCollator as a hash key.
+ }
+
+ /**
+ * Checks if argument object is equals to this object.
+ * @param target object
+ * @return true if source is equivalent to target, false otherwise
+ * @stable ICU 2.4
+ */
+ public boolean equals(Object object) {
+ if (object == this) {
+ return true;
+ }
+ if (!(object instanceof RuleBasedCollator)) {
+ return false;
+ }
+ RuleBasedCollator rhs = (RuleBasedCollator) object;
+ return getRules().equals(rhs.getRules()) &&
+ getStrength() == rhs.getStrength() &&
+ getDecomposition() == rhs.getDecomposition();
+ }
+
+ RuleBasedCollator(Locale locale) {
+ m_collator_ = NativeCollation.openCollator(locale.toString());
+ }
+
+ @Override
+ protected void finalize() {
+ NativeCollation.closeCollator(m_collator_);
+ }
+
+ private RuleBasedCollator(int addr) {
+ m_collator_ = addr;
+ }
+}
diff --git a/luni/src/main/java/com/ibm/icu4jni/util/ICU.java b/luni/src/main/java/com/ibm/icu4jni/util/ICU.java
new file mode 100644
index 0000000..b684068
--- /dev/null
+++ b/luni/src/main/java/com/ibm/icu4jni/util/ICU.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.ibm.icu4jni.util;
+
+import java.util.Locale;
+import java.util.TimeZone;
+import java.util.logging.Logger;
+
+/**
+ * Makes ICU data accessible to Java.
+ */
+public final class ICU {
+ /**
+ * Cache for ISO language names.
+ */
+ private static String[] isoLanguages;
+
+ /**
+ * Cache for ISO country names.
+ */
+ private static String[] isoCountries;
+
+ /**
+ * Available timezones cache.
+ */
+ private static String[] availableTimezones;
+
+ /**
+ * Returns an array of ISO language names (two-letter codes), fetched either
+ * from ICU's database or from our memory cache.
+ *
+ * @return The array.
+ */
+ public static String[] getISOLanguages() {
+ if (isoLanguages == null) {
+ isoLanguages = getISOLanguagesNative();
+ }
+ return isoLanguages.clone();
+ }
+
+ /**
+ * Returns an array of ISO country names (two-letter codes), fetched either
+ * from ICU's database or from our memory cache.
+ *
+ * @return The array.
+ */
+ public static String[] getISOCountries() {
+ if (isoCountries == null) {
+ isoCountries = getISOCountriesNative();
+ }
+ return isoCountries.clone();
+ }
+
+ /**
+ * Returns an array of names of timezones that are available in the system,
+ * fetched either from the TimeZone class or from our memory cache.
+ *
+ * @return The array.
+ */
+ public static String[] getKnownTimezones() {
+ if (availableTimezones == null) {
+ availableTimezones = TimeZone.getAvailableIDs();
+ }
+ return availableTimezones.clone();
+ }
+
+ /**
+ * Returns the display name for the given time zone using the given locale.
+ *
+ * @param id The time zone ID, for example "Europe/Berlin"
+ * @param daylight Indicates whether daylight savings is in use
+ * @param style The style, 0 for long, 1 for short
+ * @param locale The locale name, for example "en_US".
+ * @return The desired display name
+ */
+ public static String getDisplayTimeZone(String id, boolean daylight, int style, String locale) {
+ // If we already have the strings, linear search through them is 10x quicker than
+ // calling ICU for just the one we want.
+ if (DefaultTimeZones.locale.equals(locale)) {
+ String result = lookupDisplayTimeZone(DefaultTimeZones.names, id, daylight, style);
+ if (result != null) {
+ return result;
+ }
+ }
+ return getDisplayTimeZoneNative(id, daylight, style, locale);
+ }
+
+ public static String lookupDisplayTimeZone(String[][] zoneStrings, String id, boolean daylight, int style) {
+ for (String[] row : zoneStrings) {
+ if (row[0].equals(id)) {
+ if (daylight) {
+ return (style == TimeZone.LONG) ? row[3] : row[4];
+ } else {
+ return (style == TimeZone.LONG) ? row[1] : row[2];
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Initialization holder for default time zone names. This class will
+ * be preloaded by the zygote to share the time and space costs of setting
+ * up the list of time zone names, so although it looks like the lazy
+ * initialization idiom, it's actually the opposite.
+ */
+ private static class DefaultTimeZones {
+ /**
+ * Name of default locale at the time this class was initialized.
+ */
+ private static final String locale = Locale.getDefault().toString();
+
+ /**
+ * Names of time zones for the default locale.
+ */
+ private static final String[][] names = createTimeZoneNamesFor(locale);
+ }
+
+ /**
+ * Creates array of time zone names for the given locale. This method takes
+ * about 2s to run on a 400MHz ARM11.
+ */
+ private static String[][] createTimeZoneNamesFor(String locale) {
+ long start = System.currentTimeMillis();
+
+ /*
+ * The following code is optimized for fast native response (the time a
+ * method call can be in native code is limited). It prepares an empty
+ * array to keep native code from having to create new Java objects. It
+ * also fill in the time zone IDs to speed things up a bit. There's one
+ * array for each time zone name type. (standard/long, standard/short,
+ * daylight/long, daylight/short) The native method that fetches these
+ * strings is faster if it can do all entries of one type, before having
+ * to change to the next type. That's why the array passed down to
+ * native has 5 entries, each providing space for all time zone names of
+ * one type. Likely this access to the fields is much faster in the
+ * native code because there's less array access overhead.
+ */
+ String[][] arrayToFill = new String[5][];
+ arrayToFill[0] = getKnownTimezones();
+ arrayToFill[1] = new String[availableTimezones.length];
+ arrayToFill[2] = new String[availableTimezones.length];
+ arrayToFill[3] = new String[availableTimezones.length];
+ arrayToFill[4] = new String[availableTimezones.length];
+
+ /*
+ * Fill in the zone names in native.
+ */
+ getTimeZonesNative(arrayToFill, locale);
+
+ /*
+ * Finally we need to reorder the entries so we get the expected result.
+ */
+ String[][] result = new String[availableTimezones.length][5];
+ for (int i = 0; i < availableTimezones.length; i++) {
+ result[i][0] = arrayToFill[0][i];
+ result[i][1] = arrayToFill[1][i];
+ result[i][2] = arrayToFill[2][i];
+ result[i][3] = arrayToFill[3][i];
+ result[i][4] = arrayToFill[4][i];
+ }
+
+ Logger.global.info("Loaded time zone names for " + locale + " in "
+ + (System.currentTimeMillis() - start) + "ms.");
+
+ return result;
+ }
+
+ /**
+ * Returns the display names for all given timezones using the given locale.
+ *
+ * @return An array of time zone strings. Each row represents one time zone.
+ * The first columns holds the ID of the time zone, for example
+ * "Europe/Berlin". The other columns then hold for each row the
+ * four time zone names with and without daylight savings and in
+ * long and short format. It's exactly the array layout required by
+ * the TimeZone class.
+ */
+ public static String[][] getDisplayTimeZones(String locale) {
+ String defaultLocale = Locale.getDefault().toString();
+ if (locale == null) {
+ locale = defaultLocale;
+ }
+
+ // If locale == default and the default locale hasn't changed since
+ // DefaultTimeZones loaded, return the cached names.
+ // TODO: We should force a reboot if the default locale changes.
+ if (defaultLocale.equals(locale) && DefaultTimeZones.locale.equals(defaultLocale)) {
+ return clone2dStringArray(DefaultTimeZones.names);
+ }
+
+ return createTimeZoneNamesFor(locale);
+ }
+
+ public static String[][] clone2dStringArray(String[][] array) {
+ String[][] result = new String[array.length][];
+ for (int i = 0; i < array.length; ++i) {
+ result[i] = array[i].clone();
+ }
+ return result;
+ }
+
+ /**
+ * Returns the appropriate {@code Locale} given a {@code String} of the form returned
+ * by {@code toString}. This is very lenient, and doesn't care what's between the underscores:
+ * this method can parse strings that {@code Locale.toString} won't produce.
+ * Used to remove duplication.
+ */
+ public static Locale localeFromString(String localeName) {
+ int first = localeName.indexOf('_');
+ int second = localeName.indexOf('_', first + 1);
+ if (first == -1) {
+ // Language only ("ja").
+ return new Locale(localeName);
+ } else if (second == -1) {
+ // Language and country ("ja_JP").
+ return new Locale(localeName.substring(0, first), localeName.substring(first + 1));
+ } else {
+ // Language and country and variant ("ja_JP_TRADITIONAL").
+ return new Locale(localeName.substring(0, first), localeName.substring(first + 1, second), localeName.substring(second + 1));
+ }
+ }
+
+ public static Locale[] localesFromStrings(String[] localeNames) {
+ Locale[] result = new Locale[localeNames.length];
+ for (int i = 0; i < result.length; ++i) {
+ result[i] = localeFromString(localeNames[i]);
+ }
+ return result;
+ }
+
+ private static Locale[] availableLocalesCache;
+ public static Locale[] getAvailableLocales() {
+ if (availableLocalesCache == null) {
+ availableLocalesCache = localesFromStrings(getAvailableLocalesNative());
+ }
+ return availableLocalesCache.clone();
+ }
+
+ public static Locale[] getAvailableBreakIteratorLocales() {
+ return localesFromStrings(getAvailableBreakIteratorLocalesNative());
+ }
+
+ public static Locale[] getAvailableCalendarLocales() {
+ return localesFromStrings(getAvailableCalendarLocalesNative());
+ }
+
+ public static Locale[] getAvailableCollatorLocales() {
+ return localesFromStrings(getAvailableCollatorLocalesNative());
+ }
+
+ public static Locale[] getAvailableDateFormatLocales() {
+ return localesFromStrings(getAvailableDateFormatLocalesNative());
+ }
+
+ public static Locale[] getAvailableDateFormatSymbolsLocales() {
+ return getAvailableDateFormatLocales();
+ }
+
+ public static Locale[] getAvailableDecimalFormatSymbolsLocales() {
+ return getAvailableNumberFormatLocales();
+ }
+
+ public static Locale[] getAvailableNumberFormatLocales() {
+ return localesFromStrings(getAvailableNumberFormatLocalesNative());
+ }
+
+ // --- Native methods accessing ICU's database ----------------------------
+
+ private static native String[] getAvailableBreakIteratorLocalesNative();
+ private static native String[] getAvailableCalendarLocalesNative();
+ private static native String[] getAvailableCollatorLocalesNative();
+ private static native String[] getAvailableDateFormatLocalesNative();
+ private static native String[] getAvailableLocalesNative();
+ private static native String[] getAvailableNumberFormatLocalesNative();
+
+ public static native String getCurrencyCodeNative(String locale);
+ public static native int getCurrencyFractionDigitsNative(String currencyCode);
+ public static native String getCurrencySymbolNative(String locale, String currencyCode);
+
+ public static native String getDisplayCountryNative(String countryCode, String locale);
+ public static native String getDisplayLanguageNative(String languageCode, String locale);
+ public static native String getDisplayVariantNative(String variantCode, String locale);
+
+ public static native String getISO3CountryNative(String locale);
+ public static native String getISO3LanguageNative(String locale);
+
+ private static native String[] getISOLanguagesNative();
+ private static native String[] getISOCountriesNative();
+
+ private static native void getTimeZonesNative(String[][] arrayToFill, String locale);
+
+ private static native String getDisplayTimeZoneNative(String id, boolean isDST, int style,
+ String locale);
+
+ static native boolean initLocaleDataImpl(String locale, LocaleData result);
+}
diff --git a/luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java b/luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java
new file mode 100644
index 0000000..e27bd54
--- /dev/null
+++ b/luni/src/main/java/com/ibm/icu4jni/util/LocaleData.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.ibm.icu4jni.util;
+
+import java.text.DateFormat;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Locale;
+
+/**
+ * Passes locale-specific from ICU native code to Java.
+ *
+ *
+ */
+public final class TextAttribute extends Attribute {
+
+ /** The Constant serialVersionUID. */
+ private static final long serialVersionUID = 7744112784117861702L;
+
+ // set of available text attributes
+ /** The Constant attrMap. */
+ private static final Mapnull
to indicate an
+ * unspecified set of the properties has changed.
+ * @param oldValue
+ * the previous value of the property, or null
if
+ * the propertyName
is null
or the
+ * previous value is unknown.
+ * @param newValue
+ * the new value of the property, or null
if the
+ * propertyName
is null
or the new
+ * value is unknown..
+ * @param index
+ * the index of the property.
+ */
+ public IndexedPropertyChangeEvent(Object source, String propertyName,
+ Object oldValue, Object newValue, int index) {
+ super(source, propertyName, oldValue, newValue);
+ this.index = index;
+ }
+
+ /**
+ * Answer the index of the property that was changed in this event.
+ *
+ * @return the property element index.
+ */
+ public int getIndex() {
+ return index;
+ }
+}
diff --git a/luni/src/main/java/java/beans/PropertyChangeEvent.java b/luni/src/main/java/java/beans/PropertyChangeEvent.java
new file mode 100644
index 0000000..d614be3
--- /dev/null
+++ b/luni/src/main/java/java/beans/PropertyChangeEvent.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.beans;
+
+import java.util.EventObject;
+
+/**
+ * An event that indicates that a constraint or a boundary of a property has
+ * changed.
+ */
+public class PropertyChangeEvent extends EventObject {
+
+ private static final long serialVersionUID = 7042693688939648123L;
+
+ String propertyName;
+
+ Object oldValue;
+
+ Object newValue;
+
+ Object propagationId;
+
+ /**
+ * The constructor used to create a new {@code PropertyChangeEvent}.
+ *
+ * @param source
+ * the changed bean.
+ * @param propertyName
+ * the changed property, or null
to indicate an
+ * unspecified set of the properties has changed.
+ * @param oldValue
+ * the previous value of the property, or null
if
+ * the propertyName
is null
or the
+ * previous value is unknown.
+ * @param newValue
+ * the new value of the property, or null
if the
+ * propertyName
is null
or the new
+ * value is unknown.
+ */
+ public PropertyChangeEvent(Object source, String propertyName,
+ Object oldValue, Object newValue) {
+ super(source);
+
+ this.propertyName = propertyName;
+ this.oldValue = oldValue;
+ this.newValue = newValue;
+ }
+
+ /**
+ * Returns the name of the property that has changed. If an unspecified set
+ * of properties has changed it returns null.
+ *
+ * @return the name of the property that has changed, or null.
+ */
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ /**
+ * Sets the propagationId object.
+ *
+ * @see #getPropagationId()
+ */
+ public void setPropagationId(Object propagationId) {
+ this.propagationId = propagationId;
+ }
+
+ /**
+ * Returns the propagationId object. This is reserved for future use. Beans
+ * 1.0 demands that a listener receiving this property and then sending its
+ * own PropertyChangeEvent sets the received propagationId on the new
+ * PropertyChangeEvent's propagationId field.
+ *
+ * @return the propagationId object.
+ */
+ public Object getPropagationId() {
+ return propagationId;
+ }
+
+ /**
+ * Returns the old value that the property had. If the old value is unknown
+ * this method returns null.
+ *
+ * @return the old property value or null.
+ */
+ public Object getOldValue() {
+ return oldValue;
+ }
+
+ /**
+ * Returns the new value that the property now has. If the new value is
+ * unknown this method returns null.
+ *
+ * @return the old property value or null.
+ */
+ public Object getNewValue() {
+ return newValue;
+ }
+}
diff --git a/luni/src/main/java/java/beans/PropertyChangeListener.java b/luni/src/main/java/java/beans/PropertyChangeListener.java
new file mode 100644
index 0000000..a0a4201
--- /dev/null
+++ b/luni/src/main/java/java/beans/PropertyChangeListener.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.beans;
+
+import java.util.EventListener;
+
+/**
+ * A PropertyChangeListener can subscribe with a event source. Whenever that
+ * source raises a PropertyChangeEvent this listener will get notified.
+ */
+public interface PropertyChangeListener extends EventListener {
+
+ /**
+ * The source bean calls this method when an event is raised.
+ *
+ * @param event
+ * the {@link PropertyChangeEvent} object which contains the name
+ * and the old and new value of the property that has changed.
+ */
+ public void propertyChange(PropertyChangeEvent event);
+}
diff --git a/luni/src/main/java/java/beans/PropertyChangeListenerProxy.java b/luni/src/main/java/java/beans/PropertyChangeListenerProxy.java
new file mode 100644
index 0000000..4841b72
--- /dev/null
+++ b/luni/src/main/java/java/beans/PropertyChangeListenerProxy.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.beans;
+
+import java.util.EventListenerProxy;
+
+/**
+ * The implementation of this listener proxy just delegates the received events
+ * to its listener.
+ */
+public class PropertyChangeListenerProxy extends EventListenerProxy implements
+ PropertyChangeListener {
+
+ String propertyName;
+
+ /**
+ * Creates a new listener proxy that associates a listener with a property
+ * name.
+ *
+ * @param propertyName
+ * the name of the associated property.
+ * @param listener
+ * the listener to delegate incoming events to.
+ */
+ public PropertyChangeListenerProxy(String propertyName,
+ PropertyChangeListener listener) {
+ super(listener);
+ this.propertyName = propertyName;
+ }
+
+ /**
+ * Returns the name of the property associated with this listener proxy.
+ *
+ * @return the name of the associated property.
+ */
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public void propertyChange(PropertyChangeEvent event) {
+ PropertyChangeListener listener = (PropertyChangeListener) getListener();
+ listener.propertyChange(event);
+ }
+}
diff --git a/luni/src/main/java/java/beans/PropertyChangeSupport.java b/luni/src/main/java/java/beans/PropertyChangeSupport.java
new file mode 100644
index 0000000..32e2da6
--- /dev/null
+++ b/luni/src/main/java/java/beans/PropertyChangeSupport.java
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.beans;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This utility class
+ *
+ */
+public class PropertyChangeSupport implements Serializable {
+
+ private static final long serialVersionUID = 6401253773779951803l;
+
+ private transient Object sourceBean;
+
+ private transient ListClass instances representing object types (classes or interfaces)
+ * Classes representing primitive types
+ *
+ *
+ * Classes representing array classes
+ *
+ *
+ */
+public final class Class
If one of the doPrivileged methods is found, the walk terminate
+ * and that frame is NOT included in the returned array. Notes:
+ *
+ *
+ *
+ *
+ * @param maxDepth
+ * maximum depth to walk the stack, -1 for the entire stack
+ * @param stopAtPrivileged
+ * stop at privileged classes
+ * @return the array of the most recent classes on the stack
+ */
+ static final Class>[] getStackClasses(int maxDepth, boolean stopAtPrivileged) {
+ return VMStack.getClasses(maxDepth, stopAtPrivileged);
+ }
+
+}
diff --git a/luni/src/main/java/java/lang/ClassCache.java b/luni/src/main/java/java/lang/ClassCache.java
new file mode 100644
index 0000000..5ea6992
--- /dev/null
+++ b/luni/src/main/java/java/lang/ClassCache.java
@@ -0,0 +1,702 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.lang;
+
+import org.apache.harmony.kernel.vm.LangAccess;
+import org.apache.harmony.kernel.vm.ReflectionAccess;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.HashSet;
+
+/**
+ * Cache of per-class data, meant to help the performance of reflection
+ * methods.
+ *
+ *