index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/server/DefaultAxisServerFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.server; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.AxisProperties; import org.apache.axis.EngineConfiguration; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.File; import java.util.Map; /** * Helper class for obtaining AxisServers. Default implementation. * * @author Glen Daniels (gdaniels@apache.org) */ public class DefaultAxisServerFactory implements AxisServerFactory { protected static Log log = LogFactory.getLog(DefaultAxisServerFactory.class.getName()); /** * Get an AxisServer. * <p> * Factory obtains EngineConfiguration as first found of the following: * a) EngineConfiguration instance, keyed to * EngineConfiguration.PROPERTY_NAME in 'environment', or * b) EngineConfiguration class name, keyed to * AxisEngine.PROP_DEFAULT_CONFIG_CLASS in AxisProperties. * Class is instantiated if found. * <p> * If an EngineConfiguration cannot be located, the default * AxisServer constructor is used. * <p> * The AxisServer's option AxisEngine.PROP_ATTACHMENT_DIR is set to * the (first found) value of either AxisEngine.ENV_ATTACHMENT_DIR * or AxisEngine.ENV_SERVLET_REALPATH. * * @param environment The following keys are used: * AxisEngine.ENV_ATTACHMENT_DIR * - Set as default value for Axis option * AxisEngine.PROP_ATTACHMENT_DIR * AxisEngine.ENV_SERVLET_REALPATH * - Set as alternate default value for Axis option * AxisEngine.PROP_ATTACHMENT_DIR * EngineConfiguration.PROPERTY_NAME * - Instance of EngineConfiguration, * if not set then an attempt is made to retreive * a class name from AxisEngine.PROP_CONFIG_CLASS */ public AxisServer getServer(Map environment) throws AxisFault { log.debug("Enter: DefaultAxisServerFactory::getServer"); AxisServer ret = createServer(environment); if (ret != null) { if (environment != null) { ret.setOptionDefault(AxisEngine.PROP_ATTACHMENT_DIR, (String)environment.get(AxisEngine.ENV_ATTACHMENT_DIR)); ret.setOptionDefault(AxisEngine.PROP_ATTACHMENT_DIR, (String)environment.get(AxisEngine.ENV_SERVLET_REALPATH)); } String attachmentsdir = (String)ret.getOption(AxisEngine.PROP_ATTACHMENT_DIR); if (attachmentsdir != null) { File attdirFile = new File(attachmentsdir); if (!attdirFile.isDirectory()) { attdirFile.mkdirs(); } } } log.debug("Exit: DefaultAxisServerFactory::getServer"); return ret; } /** * Do the actual work of creating a new AxisServer, using the * configuration, or using the default constructor if null is passed. * * @return a shiny new AxisServer, ready for use. */ private static AxisServer createServer(Map environment) { EngineConfiguration config = getEngineConfiguration(environment); // Return new AxisServer using the appropriate config return (config == null) ? new AxisServer() : new AxisServer(config); } /** * Look for EngineConfiguration, it is first of: * a) EngineConfiguration instance, keyed to * EngineConfiguration.PROPERTY_NAME in 'environment', or * b) EngineConfiguration class name, keyed to * AxisEngine.PROP_DEFAULT_CONFIG_CLASS in AxisProperties. * Class is instantiated if found. */ private static EngineConfiguration getEngineConfiguration(Map environment) { log.debug("Enter: DefaultAxisServerFactory::getEngineConfiguration"); EngineConfiguration config = null; if (environment != null) { try { config = (EngineConfiguration)environment.get(EngineConfiguration.PROPERTY_NAME); } catch (ClassCastException e) { log.warn(Messages.getMessage("engineConfigWrongClass00"), e); // Fall through } } if (config == null) { // A default engine configuration class may be set in a system // property. If so, try creating an engine configuration. String configClass = AxisProperties.getProperty(AxisEngine.PROP_DEFAULT_CONFIG_CLASS); if (configClass != null) { try { // Got one - so try to make it (which means it had better have // a default constructor - may make it possible later to pass // in some kind of environmental parameters...) Class cls = ClassUtils.forName(configClass); config = (EngineConfiguration)cls.newInstance(); } catch (ClassNotFoundException e) { log.warn(Messages.getMessage("engineConfigNoClass00", configClass), e); // Fall through } catch (InstantiationException e) { log.warn(Messages.getMessage("engineConfigNoInstance00", configClass), e); // Fall through } catch (IllegalAccessException e) { log.warn(Messages.getMessage("engineConfigIllegalAccess00", configClass), e); // Fall through } catch (ClassCastException e) { log.warn(Messages.getMessage("engineConfigWrongClass01", configClass), e); // Fall through } } } log.debug("Exit: DefaultAxisServerFactory::getEngineConfiguration"); return config; } }
7,600
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/IOUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.IOException; import java.io.InputStream; /** * Utility class containing IO helper methods */ public class IOUtils { private IOUtils() { } /** * Read into a byte array; tries to ensure that the the * full buffer is read. * * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt> * @see #readFully(java.io.InputStream, byte[], int, int) */ public static int readFully(InputStream in, byte[] b) throws IOException { return readFully(in, b, 0, b.length); } /** * Same as the normal <tt>in.read(b, off, len)</tt>, but tries to ensure that * the entire len number of bytes is read. * <p> * @return the number of bytes read, or -1 if the end of file is * reached before any bytes are read */ public static int readFully(InputStream in, byte[] b, int off, int len) throws IOException { int total = 0; for (;;) { int got = in.read(b, off + total, len - total); if (got < 0) { return (total == 0) ? -1 : total; } else { total += got; if (total == len) return total; } } } }
7,601
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/StringUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.InternalException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.io.Writer; import java.io.IOException; import java.io.StringWriter; public class StringUtils { private StringUtils() { } /** * An empty immutable <code>String</code> array. */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Tests if this string starts with the specified prefix (Ignoring whitespaces) * @param prefix * @param string * @return boolean */ public static boolean startsWithIgnoreWhitespaces(String prefix, String string) { int index1 = 0; int index2 = 0; int length1 = prefix.length(); int length2 = string.length(); char ch1 = ' '; char ch2 = ' '; while (index1 < length1 && index2 < length2) { while (index1 < length1 && Character.isWhitespace(ch1 = prefix.charAt(index1))) { index1++; } while (index2 < length2 && Character.isWhitespace(ch2 = string.charAt(index2))) { index2++; } if (index1 == length1 && index2 == length2) { return true; } if (ch1 != ch2) { return false; } index1++; index2++; } if(index1 < length1 && index2 >= length2) return false; return true; } /** * <p>Splits the provided text into an array, separator specified. * This is an alternative to using StringTokenizer.</p> * * <p>The separator is not included in the returned String array. * Adjacent separators are treated as one separator.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.split(null, *) = null * StringUtils.split("", *) = [] * StringUtils.split("a.b.c", '.') = ["a", "b", "c"] * StringUtils.split("a..b.c", '.') = ["a", "b", "c"] * StringUtils.split("a:b:c", '.') = ["a:b:c"] * StringUtils.split("a\tb\nc", null) = ["a", "b", "c"] * StringUtils.split("a b c", ' ') = ["a", "b", "c"] * </pre> * * @param str the String to parse, may be null * @param separatorChar the character used as the delimiter, * <code>null</code> splits on whitespace * @return an array of parsed Strings, <code>null</code> if null String input */ public static String[] split(String str, char separatorChar) { if (str == null) { return null; } int len = str.length(); if (len == 0) { return EMPTY_STRING_ARRAY; } List list = new ArrayList(); int i = 0, start = 0; boolean match = false; while (i < len) { if (str.charAt(i) == separatorChar) { if (match) { list.add(str.substring(start, i)); match = false; } start = ++i; continue; } match = true; i++; } if (match) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } /** * Joins the elements of the provided collection into a single string using * the given separator. * * @param items * the collection of strings to join together * @param separatorChar * the separator character to use * @return the joined string */ public static String join(Collection items, char separatorChar) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (Iterator it = items.iterator(); it.hasNext(); ) { if (first) { first = false; } else { buffer.append(separatorChar); } buffer.append((String)it.next()); } return buffer.toString(); } // Empty checks //----------------------------------------------------------------------- /** * <p>Checks if a String is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().</p> * * @param str the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } // Stripping //----------------------------------------------------------------------- /** * <p>Strips whitespace from the start and end of a String.</p> * * <p>This removes whitespace. Whitespace is defined by * {@link Character#isWhitespace(char)}.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.strip(null) = null * StringUtils.strip("") = "" * StringUtils.strip(" ") = "" * StringUtils.strip("abc") = "abc" * StringUtils.strip(" abc") = "abc" * StringUtils.strip("abc ") = "abc" * StringUtils.strip(" abc ") = "abc" * StringUtils.strip(" ab c ") = "ab c" * </pre> * * @param str the String to remove whitespace from, may be null * @return the stripped String, <code>null</code> if null String input */ public static String strip(String str) { return strip(str, null); } /** * <p>Strips any of a set of characters from the start and end of a String. * This is similar to {@link String#trim()} but allows the characters * to be stripped to be controlled.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}. * Alternatively use {@link #strip(String)}.</p> * * <pre> * StringUtils.strip(null, *) = null * StringUtils.strip("", *) = "" * StringUtils.strip("abc", null) = "abc" * StringUtils.strip(" abc", null) = "abc" * StringUtils.strip("abc ", null) = "abc" * StringUtils.strip(" abc ", null) = "abc" * StringUtils.strip(" abcyx", "xyz") = " abc" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String strip(String str, String stripChars) { if (str == null) { return str; } int len = str.length(); if (len == 0) { return str; } int start = getStripStart(str, stripChars); if (start == len) { return ""; } int end = getStripEnd(str, stripChars); return (start == 0 && end == len) ? str : str.substring(start, end); } /** * <p>Strips any of a set of characters from the start of a String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripStart(null, *) = null * StringUtils.stripStart("", *) = "" * StringUtils.stripStart("abc", "") = "abc" * StringUtils.stripStart("abc", null) = "abc" * StringUtils.stripStart(" abc", null) = "abc" * StringUtils.stripStart("abc ", null) = "abc " * StringUtils.stripStart(" abc ", null) = "abc " * StringUtils.stripStart("yxabc ", "xyz") = "abc " * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String stripStart(String str, String stripChars) { int start = getStripStart(str, stripChars); return (start <= 0) ? str : str.substring(start); } private static int getStripStart(String str, String stripChars) { int strLen; if (str == null || (strLen = str.length()) == 0) { return -1; } int start = 0; if (stripChars == null) { while ((start != strLen) && Character.isWhitespace(str.charAt(start))) { start++; } } else if (stripChars.length() == 0) { return start; } else { while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) { start++; } } return start; } /** * <p>Strips any of a set of characters from the end of a String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String stripEnd(String str, String stripChars) { int end = getStripEnd(str, stripChars); return (end < 0) ? str : str.substring(0, end); } private static int getStripEnd(String str, String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return -1; } if (stripChars == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.length() == 0) { return end; } else { while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) { end--; } } return end; } /** * write the escaped version of a given string * * @param str string to be encoded * @return a new escaped <code>String</code>, <code>null</code> if null string input */ public static String escapeNumericChar(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length()); escapeNumericChar(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter ioe.printStackTrace(); return null; } } /** * write the escaped version of a given string * * @param out writer to write this string to * @param str string to be encoded */ public static void escapeNumericChar(Writer out, String str) throws IOException { if (str == null) { return; } int length = str.length(); char character; for (int i = 0; i < length; i++) { character = str.charAt( i ); if (character > 0x7F) { out.write("&#x"); out.write(Integer.toHexString(character).toUpperCase()); out.write(";"); } else { out.write(character); } } } /** * <p>Unescapes numeric character referencs found in the <code>String</code>.</p> * * <p>For example, it will return a unicode string which means the specified numeric * character references looks like "&amp;#x3088;&amp;#x3046;&amp;#x3053;&amp;#x305d;".</p> * * @param str the <code>String</code> to unescape, may be null * @return a new unescaped <code>String</code>, <code>null</code> if null string input */ public static String unescapeNumericChar(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length()); unescapeNumericChar(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter ioe.printStackTrace(); return null; } } /** * <p>Unescapes numeric character references found in the <code>String</code> to a * <code>Writer</code>.</p> * * <p>For example, it will return a unicode string which means the specified numeric * character references looks like "&amp;#x3088;&amp;#x3046;&amp;#x3053;&amp;#x305d;".</p> * * <p>A <code>null</code> string input has no effect.</p> * * @param out the <code>Writer</code> used to output unescaped characters * @param str the <code>String</code> to unescape, may be null * @throws IllegalArgumentException if the Writer is <code>null</code> * @throws java.io.IOException if error occurs on underlying Writer */ public static void unescapeNumericChar(Writer out, String str) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz = str.length(); StringBuffer unicode = new StringBuffer(4); StringBuffer escapes = new StringBuffer(3); boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == 4) { // unicode now contains the four hex digits // which represents our unicode character try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); unicode.setLength(0); // need to skip the delimiter - ';' i = i + 1; inUnicode = false; } catch (NumberFormatException nfe) { throw new InternalException(nfe); } } continue; } else if (ch=='&') { // Start of the escape sequence ... // At least, the numeric character references require 8 bytes to // describe a Unicode character like as"&#xFFFF;" if (i+7 <= sz) { escapes.append(ch); escapes.append(str.charAt(i+1)); escapes.append(str.charAt(i+2)); if (escapes.toString().equals("&#x") && str.charAt(i+7)==';') { inUnicode = true; } else { out.write(escapes.toString()); } escapes.setLength(0); // need to skip the escaping chars - '&#x' i = i + 2; } else { out.write(ch); } continue; } out.write(ch); } } }
7,602
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/IdentityHashMap.java
/** * Created by IntelliJ IDEA. * User: srida01 * Date: Dec 2, 2002 * Time: 10:38:46 AM * To change this template use Options | File Templates. */ package org.apache.axis.utils; import java.util.HashMap; import java.util.Map; /** * IdentityHashMap similar to JDK1.4's java.util.IdentityHashMap * @author Davanum Srinivas (dims@yahoo.com) */ public class IdentityHashMap extends HashMap { /** * Constructor for IdentityHashMap. * @param initialCapacity * @param loadFactor */ public IdentityHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor for IdentityHashMap. * @param initialCapacity */ public IdentityHashMap(int initialCapacity) { super(initialCapacity); } /** * Constructor for IdentityHashMap. */ public IdentityHashMap() { super(); } /** * Constructor for IdentityHashMap. * @param t */ public IdentityHashMap(Map t) { super(t); } /** * @see Map#get(Object) */ public Object get(Object key) { return super.get(new IDKey(key)); } /** * @see Map#put(Object, Object) */ public Object put(Object key, Object value) { return super.put(new IDKey(key), value); } /** * adds an object to the Map. new Identity(obj) is used as key */ public Object add(Object value) { Object key = new IDKey(value); if (! super.containsKey(key)) { return super.put(key, value); } else return null; } /** * @see Map#remove(Object) */ public Object remove(Object key) { return super.remove(new IDKey(key)); } /** * @see Map#containsKey(Object) */ public boolean containsKey(Object key) { return super.containsKey(new IDKey(key)); } }
7,603
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/Base64.java
/* * Copyright 1999,2004 The Apache Software Foundation. * * 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.axis.utils; /** * Unceremoniously lifted from * jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/Base64.java * Revision 1.8 2002/01/05 11:15:59 * * Eliminates dependency on sun.misc.Base64Encoding, * which isn't appreciated by the J2EE security manager. * (it's an access exception to load sun.misc.* classes * in application code). * * <p>Base64 encoder and decoder.</p> * <p> * This class provides encoding/decoding methods for * the Base64 encoding as defined by RFC 2045, * N. Freed and N. Borenstein. * RFC 2045: Multipurpose Internet Mail Extensions (MIME) * Part One: Format of Internet Message Bodies. Reference * 1996. Available at: http://www.ietf.org/rfc/rfc2045.txt * </p> * @author Jeffrey Rodriguez */ final class Base64 { private static final int BASELENGTH = 255; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int SIXBIT = 6; private static final int FOURBYTE = 4; private static final int SIGN = -128; private static final byte PAD = ( byte ) '='; private static byte [] base64Alphabet = new byte[BASELENGTH]; private static byte [] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; static { for (int i = 0; i<BASELENGTH; i++ ) { base64Alphabet[i] = -1; } for ( int i = 'Z'; i >= 'A'; i-- ) { base64Alphabet[i] = (byte) (i-'A'); } for ( int i = 'z'; i>= 'a'; i--) { base64Alphabet[i] = (byte) ( i-'a' + 26); } for ( int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i-'0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i<=25; i++ ) { lookUpBase64Alphabet[i] = (byte) ('A'+i ); } for (int i = 26, j = 0; i<=51; i++, j++ ) { lookUpBase64Alphabet[i] = (byte) ('a'+ j ); } for (int i = 52, j = 0; i<=61; i++, j++ ) { lookUpBase64Alphabet[i] = (byte) ('0' + j ); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } static boolean isBase64( String isValidString ){ return( isArrayByteBase64( isValidString.getBytes())); } static boolean isBase64( byte octect ) { // Should we ignore white space? return(octect == PAD || base64Alphabet[octect] != -1 ); } static boolean isArrayByteBase64( byte[] arrayOctect ) { int length = arrayOctect.length; if ( length == 0 ) { return true; } for ( int i=0; i < length; i++ ) { if ( Base64.isBase64( arrayOctect[i] ) == false) { return false; } } return true; } /** * Encodes hex octects into Base64 * * @param binaryData Array containing binaryData * @return Base64-encoded array */ static byte[] encode( byte[] binaryData ) { int lengthDataBits = binaryData.length*EIGHTBIT; int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; byte encodedData[] = null; if ( fewerThan24bits != 0 ) { //data not divisible by 24 bit encodedData = new byte[ (numberTriplets + 1 )*4 ]; } else { // 16 or 8 bit encodedData = new byte[ numberTriplets*4 ]; } byte k=0, l=0, b1=0,b2=0,b3=0; int encodedIndex = 0; int dataIndex = 0; int i = 0; for ( i = 0; i<numberTriplets; i++ ) { dataIndex = i*3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; l = (byte)(b2 & 0x0f); k = (byte)(b1 & 0x03); encodedIndex = i*4; byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex+1] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; encodedData[encodedIndex+2] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; encodedData[encodedIndex+3] = lookUpBase64Alphabet[ b3 & 0x3f ]; } // form integral number of 6-bit groups dataIndex = i*3; encodedIndex = i*4; if (fewerThan24bits == EIGHTBIT ) { b1 = binaryData[dataIndex]; k = (byte) ( b1 &0x03 ); byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ k<<4 ]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if ( fewerThan24bits == SIXTEENBIT ) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex +1 ]; l = ( byte ) ( b2 &0x0f ); k = ( byte ) ( b1 &0x03 ); byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[ val1 ]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[ l<<2 ]; encodedData[encodedIndex + 3] = PAD; } return encodedData; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ static byte[] decode( byte[] base64Data ) { // Should we throw away anything not in base64Data ? // handle the edge case, so we don't have to worry about it later if(base64Data.length == 0) { return new byte[0]; } int numberQuadruple = base64Data.length/FOURBYTE; byte decodedData[] = null; byte b1=0,b2=0,b3=0, b4=0, marker0=0, marker1=0; int encodedIndex = 0; int dataIndex = 0; { // this block sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while(base64Data[lastData-1] == PAD) { if(--lastData == 0) { return new byte[0]; } } decodedData = new byte[ lastData - numberQuadruple ]; } for (int i = 0; i<numberQuadruple; i++ ) { dataIndex = i*4; marker0 = base64Data[dataIndex +2]; marker1 = base64Data[dataIndex +3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex +1]]; if ( marker0 != PAD && marker1 != PAD ) { //No PAD e.g 3cQl b3 = base64Alphabet[ marker0 ]; b4 = base64Alphabet[ marker1 ]; decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); decodedData[encodedIndex+2] = (byte)( b3<<6 | b4 ); } else if ( marker0 == PAD ) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; } else if ( marker1 == PAD ) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[ marker0 ]; decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ); decodedData[encodedIndex+1] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); } encodedIndex += 3; } return decodedData; } }
7,604
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/NetworkUtils.java
/* * Copyright 2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.commons.logging.Log; import org.apache.axis.components.logger.LogFactory; import java.net.InetAddress; import java.net.UnknownHostException; /** * Utility classes for networking * created 13-May-2004 16:17:51 */ public class NetworkUtils { /** * what we return when we cannot determine our hostname. * We use this rather than 'localhost' as if DNS is very confused, * localhost can map to different machines than "self". */ public static final String LOCALHOST = "127.0.0.1"; /** * loopback address in IPV6 */ public static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1"; /** * keep this uninstantiable. */ private NetworkUtils() { } protected static Log log = LogFactory.getLog(NetworkUtils.class.getName()); /** * Get the string defining the hostname of the system, as taken from * the default network adapter of the system. There is no guarantee that * this will be fully qualified, or that it is the hostname used by external * machines to access the server. * If we cannot determine the name, then we return the default hostname, * which is defined by {@link #LOCALHOST} * @return a string name of the host. */ public static String getLocalHostname() { InetAddress address; String hostname; try { address = InetAddress.getLocalHost(); //force a best effort reverse DNS lookup hostname = address.getHostName(); if (hostname == null || hostname.length() == 0) { hostname = address.toString(); } } catch (UnknownHostException noIpAddrException) { //this machine is not on a LAN, or DNS is unhappy //return the default hostname if(log.isDebugEnabled()) { log.debug("Failed to lookup local IP address",noIpAddrException); } hostname = LOCALHOST; } return hostname; } }
7,605
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/Admin.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils ; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.WSDDEngineConfiguration; import org.apache.axis.client.AxisClient; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.WSDDConstants; import org.apache.axis.deployment.wsdd.WSDDDeployment; import org.apache.axis.deployment.wsdd.WSDDDocument; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.server.AxisServer; import org.apache.axis.utils.NetworkUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import java.io.FileInputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; /** * Handy static utility functions for turning XML into * Axis deployment operations. * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) */ public class Admin { protected static Log log = LogFactory.getLog(Admin.class.getName()); /** * Process a given XML document - needs cleanup. */ public Element[] AdminService(Element [] xml) throws Exception { log.debug("Enter: Admin::AdminService"); MessageContext msgContext = MessageContext.getCurrentContext(); Document doc = process( msgContext, xml[0] ); Element[] result = new Element[1]; result[0] = doc.getDocumentElement(); log.debug("Exit: Admin::AdminService"); return result; } protected static Document processWSDD(MessageContext msgContext, AxisEngine engine, Element root) throws Exception { Document doc = null ; String action = root.getLocalName(); if (action.equals("passwd")) { String newPassword = root.getFirstChild().getNodeValue(); engine.setAdminPassword(newPassword); doc = XMLUtils.newDocument(); doc.appendChild( root = doc.createElementNS("", "Admin" ) ); root.appendChild( doc.createTextNode( Messages.getMessage("done00") ) ); return doc; } if (action.equals("quit")) { log.error(Messages.getMessage("quitRequest00")); if (msgContext != null) { // put a flag into message context so listener will exit after // sending response msgContext.setProperty(MessageContext.QUIT_REQUESTED, "true"); } doc = XMLUtils.newDocument(); doc.appendChild( root = doc.createElementNS("", "Admin" ) ); root.appendChild( doc.createTextNode( Messages.getMessage("quit00", "") ) ); return doc; } if ( action.equals("list") ) { return listConfig(engine); } if (action.equals("clientdeploy")) { // set engine to client engine engine = engine.getClientEngine(); } WSDDDocument wsddDoc = new WSDDDocument(root); EngineConfiguration config = engine.getConfig(); if (config instanceof WSDDEngineConfiguration) { WSDDDeployment deployment = ((WSDDEngineConfiguration)config).getDeployment(); wsddDoc.deploy(deployment); } engine.refreshGlobalOptions(); engine.saveConfiguration(); doc = XMLUtils.newDocument(); doc.appendChild( root = doc.createElementNS("", "Admin" ) ); root.appendChild( doc.createTextNode( Messages.getMessage("done00") ) ); return doc; } /** * The meat of the Admin service. Process an xML document rooted with * a "deploy", "undeploy", "list", or "quit" element. * * @param msgContext the MessageContext we're processing * @param root the root Element of the XML * @return an XML Document indicating the results. */ public Document process(MessageContext msgContext, Element root) throws Exception { // Check security FIRST. /** Might do something like this once security is a little more * integrated. if (!engine.hasSafePassword() && !action.equals("passwd")) throw new AxisFault("Server.MustSetPassword", "You must change the admin password before administering Axis!", null, null); */ verifyHostAllowed(msgContext); String rootNS = root.getNamespaceURI(); AxisEngine engine = msgContext.getAxisEngine(); // If this is WSDD, process it correctly. if (rootNS != null && rootNS.equals(WSDDConstants.URI_WSDD)) { return processWSDD(msgContext, engine, root); } // Else fault // TODO: Better handling here throw new Exception(Messages.getMessage("adminServiceNoWSDD")); } /** * host validation logic goes here * @param msgContext * @throws AxisFault */ private void verifyHostAllowed(MessageContext msgContext) throws AxisFault { /** For now, though - make sure we can only admin from our own * IP, unless the remoteAdmin option is set. */ Handler serviceHandler = msgContext.getService(); if (serviceHandler != null && !JavaUtils.isTrueExplicitly(serviceHandler.getOption("enableRemoteAdmin"))) { String remoteIP = msgContext.getStrProp(Constants.MC_REMOTE_ADDR); if (remoteIP != null && !(remoteIP.equals(NetworkUtils.LOCALHOST) || remoteIP.equals(NetworkUtils.LOCALHOST_IPV6))) { try { InetAddress myAddr = InetAddress.getLocalHost(); InetAddress remoteAddr = InetAddress.getByName(remoteIP); if(log.isDebugEnabled()) { log.debug("Comparing remote caller " + remoteAddr +" to "+ myAddr); } if (!myAddr.equals(remoteAddr)) { log.error(Messages.getMessage("noAdminAccess01", remoteAddr.toString())); throw new AxisFault("Server.Unauthorized", Messages.getMessage("noAdminAccess00"), null, null); } } catch (UnknownHostException e) { throw new AxisFault("Server.UnknownHost", Messages.getMessage("unknownHost00"), null, null); } } } } /** Get an XML document representing this engine's configuration. * * This document is suitable for saving and reloading into the * engine. * * @param engine the AxisEngine to work with * @return an XML document holding the engine config * @exception AxisFault */ public static Document listConfig(AxisEngine engine) throws AxisFault { StringWriter writer = new StringWriter(); SerializationContext context = new SerializationContext(writer); context.setPretty(true); try { EngineConfiguration config = engine.getConfig(); if (config instanceof WSDDEngineConfiguration) { WSDDDeployment deployment = ((WSDDEngineConfiguration)config).getDeployment(); deployment.writeToContext(context); } } catch (Exception e) { // If the engine config isn't a FileProvider, or we have no // engine config for some odd reason, we'll end up here. throw new AxisFault(Messages.getMessage("noEngineWSDD")); } try { writer.close(); return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString()))); } catch (Exception e) { log.error("exception00", e); return null; } } public static void main(String args[]) throws Exception { int i = 0 ; if ( args.length < 2 || !(args[0].equals("client") || args[0].equals("server")) ) { log.error( Messages.getMessage("usage00", "Admin client|server <xml-file>") ); log.error( Messages.getMessage("where00", "<xml-file>") ); log.error( "<deploy>" ); /* log.error( " <transport name=a request=\"a,b,c\" sender=\"s\""); log.error( " response=\"d,e\"/>" ); */ log.error( " <handler name=a class=className/>" ); log.error( " <chain name=a flow=\"a,b,c\" />" ); log.error( " <chain name=a request=\"a,b,c\" pivot=\"d\"" ); log.error( " response=\"e,f,g\" />" ); log.error( " <service name=a handler=b />" ); log.error( "</deploy>" ); log.error( "<undeploy>" ); log.error( " <handler name=a/>" ); log.error( " <chain name=a/>" ); log.error( " <service name=a/>" ); log.error( "</undeploy>" ); log.error( "<list/>" ); // throw an Exception which will go uncaught! this way, a test // suite can invoke main() and detect the exception throw new IllegalArgumentException( Messages.getMessage("usage00", "Admin client|server <xml-file>")); // System.exit( 1 ); } Admin admin = new Admin(); AxisEngine engine; if ( args[0].equals("client") ) engine = new AxisClient(); else engine = new AxisServer(); engine.setShouldSaveConfig(true); engine.init(); MessageContext msgContext = new MessageContext(engine); try { for ( i = 1 ; i < args.length ; i++ ) { if (log.isDebugEnabled()) log.debug( Messages.getMessage("process00", args[i]) ); Document doc = XMLUtils.newDocument( new FileInputStream( args[i] ) ); Document result = admin.process(msgContext, doc.getDocumentElement()); if (result != null) { System.out.println(XMLUtils.DocumentToString(result)); } } } catch( Exception e ) { log.error( Messages.getMessage("errorProcess00", args[i]), e ); throw e; } } }
7,606
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/URLHashSet.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.File; import java.net.URL; import java.util.HashSet; import java.util.StringTokenizer; /** * Class URLHashSet * * @author Davanum Srinivas (dims@apache.org) */ public class URLHashSet extends HashSet { /** * Adds the specified URL to this set if it is not already present. * * @param url url to be added to this set. * @return true if the set did not already contain the specified element. */ public boolean add(URL url) { return super.add(normalize(url)); } /** * Removes the given URL from this set if it is present. * * @param url url to be removed from this set, if present. * @return true if the set contained the specified element. */ public boolean remove(URL url) { return super.remove(normalize(url)); } /** * Returns true if this set contains the specified element. * * @param url url whose presence in this set is to be tested. * @return true if this set contains the specified element. */ public boolean contains(URL url) { return super.contains(normalize(url)); } /** * if the url points to a file then make sure we cleanup ".." "." etc. * * @param url url to be normalized * @return normalized url */ public static URL normalize(URL url) { if (url.getProtocol().equals("file")) { try { File f = new File(cleanup(url.getFile())); if(f.exists()) return f.toURL(); } catch (Exception e) {} } return url; } /** * Normalize a uri containing ../ and ./ paths. * * @param uri The uri path to normalize * @return The normalized uri */ private static String cleanup(String uri) { String[] dirty = tokenize(uri, "/\\", false); int length = dirty.length; String[] clean = new String[length]; boolean path; boolean finished; while (true) { path = false; finished = true; for (int i = 0, j = 0; (i < length) && (dirty[i] != null); i++) { if (".".equals(dirty[i])) { // ignore } else if ("..".equals(dirty[i])) { clean[j++] = dirty[i]; if (path) { finished = false; } } else { if ((i + 1 < length) && ("..".equals(dirty[i + 1]))) { i++; } else { clean[j++] = dirty[i]; path = true; } } } if (finished) { break; } else { dirty = clean; clean = new String[length]; } } StringBuffer b = new StringBuffer(uri.length()); for (int i = 0; (i < length) && (clean[i] != null); i++) { b.append(clean[i]); if ((i + 1 < length) && (clean[i + 1] != null)) { b.append("/"); } } return b.toString(); } /** * Constructs a string tokenizer for the specified string. All characters * in the delim argument are the delimiters for separating tokens. * If the returnTokens flag is true, then the delimiter characters are * also returned as tokens. Each delimiter is returned as a string of * length one. If the flag is false, the delimiter characters are skipped * and only serve as separators between tokens. Then tokenizes the str * and return an String[] array with tokens. * * @param str a string to be parsed * @param delim the delimiters * @param returnTokens flag indicating whether to return the delimiters * as tokens * * @return array with tokens */ private static String[] tokenize(String str, String delim, boolean returnTokens) { StringTokenizer tokenizer = new StringTokenizer(str, delim, returnTokens); String[] tokens = new String[tokenizer.countTokens()]; int i = 0; while (tokenizer.hasMoreTokens()) { tokens[i] = tokenizer.nextToken(); i++; } return tokens; } }
7,607
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/DefaultEntityResolver.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.xml.sax.InputSource; public class DefaultEntityResolver implements org.xml.sax.EntityResolver { public static final DefaultEntityResolver INSTANCE = new DefaultEntityResolver(); private DefaultEntityResolver() { } public InputSource resolveEntity(String publicId, String systemId) { return XMLUtils.getEmptyInputSource(); } }
7,608
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/XMLUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils ; import org.apache.axis.AxisEngine; import org.apache.axis.Constants; import org.apache.axis.InternalException; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.AxisProperties; import org.apache.axis.components.encoding.XMLEncoder; import org.apache.axis.components.encoding.XMLEncoderFactory; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; import java.util.Iterator; import java.util.List; import java.util.Stack; public class XMLUtils { protected static Log log = LogFactory.getLog(XMLUtils.class.getName()); public static final String httpAuthCharEncoding = "ISO-8859-1"; private static final String saxParserFactoryProperty = "javax.xml.parsers.SAXParserFactory"; private static DocumentBuilderFactory dbf = getDOMFactory(); private static SAXParserFactory saxFactory; private static Stack saxParsers = new Stack(); private static DefaultHandler doNothingContentHandler = new DefaultHandler(); private static String EMPTY = ""; private static ByteArrayInputStream bais = new ByteArrayInputStream(EMPTY.getBytes()); private static boolean tryReset= true; protected static boolean enableParserReuse = false; private static class ThreadLocalDocumentBuilder extends ThreadLocal { protected Object initialValue() { try { return getDOMFactory().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error(Messages.getMessage("parserConfigurationException00"), e); } return null; } } private static ThreadLocalDocumentBuilder documentBuilder = new ThreadLocalDocumentBuilder(); static { // Initialize SAX Parser factory defaults initSAXFactory(null, true, false); String value = AxisProperties.getProperty(AxisEngine.PROP_XML_REUSE_SAX_PARSERS, "" + true); if (value.equalsIgnoreCase("true") || value.equals("1") || value.equalsIgnoreCase("yes")) { enableParserReuse = true; } else { enableParserReuse = false; } } /** * Encode a string appropriately for XML. * @param orig the String to encode * @return a String in which XML special chars are repalced by entities */ public static String xmlEncodeString(String orig) { XMLEncoder encoder = getXMLEncoder(MessageContext.getCurrentContext()); return encoder.encode(orig); } /** * Get the current XMLEncoder * @return XMLEncoder */ public static XMLEncoder getXMLEncoder(MessageContext msgContext) { return getXMLEncoder(getEncoding(null, msgContext)); } /** * Get the XMLEncoder for specific encoding * @return XMLEncoder */ public static XMLEncoder getXMLEncoder(String encoding) { XMLEncoder encoder = null; try { encoder = XMLEncoderFactory.getEncoder(encoding); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); encoder = XMLEncoderFactory.getDefaultEncoder(); } return encoder; } /** * Get the current encoding in effect * @return string */ public static String getEncoding(MessageContext msgContext) { XMLEncoder encoder = getXMLEncoder(msgContext); return encoder.getEncoding(); } /** * Get the current encoding in effect * @return string */ public static String getEncoding() { XMLEncoder encoder = getXMLEncoder(MessageContext.getCurrentContext()); return encoder.getEncoding(); } /** Initialize the SAX parser factory. * * @param factoryClassName The (optional) class name of the desired * SAXParserFactory implementation. Will be * assigned to the system property * <b>javax.xml.parsers.SAXParserFactory</b> * unless this property is already set. * If <code>null</code>, leaves current setting * alone. * @param namespaceAware true if we want a namespace-aware parser * @param validating true if we want a validating parser * */ public static void initSAXFactory(String factoryClassName, boolean namespaceAware, boolean validating) { if (factoryClassName != null) { try { saxFactory = (SAXParserFactory)Class.forName(factoryClassName). newInstance(); /* * Set the system property only if it is not already set to * avoid corrupting environments in which Axis is embedded. */ if (System.getProperty(saxParserFactoryProperty) == null) { System.setProperty(saxParserFactoryProperty, factoryClassName); } } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); saxFactory = null; } } else { saxFactory = SAXParserFactory.newInstance(); } saxFactory.setNamespaceAware(namespaceAware); saxFactory.setValidating(validating); // Discard existing parsers saxParsers.clear(); } private static DocumentBuilderFactory getDOMFactory() { DocumentBuilderFactory dbf; try { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); } catch( Exception e ) { log.error(Messages.getMessage("exception00"), e ); dbf = null; } return( dbf ); } /** * Gets a DocumentBuilder * @return DocumentBuilder * @throws ParserConfigurationException */ public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { return (DocumentBuilder) documentBuilder.get(); } /** * Releases a DocumentBuilder * @param db */ public static void releaseDocumentBuilder(DocumentBuilder db) { try { db.setErrorHandler(null); // setting implementation default } catch (Throwable t) { log.debug("Failed to set ErrorHandler to null on DocumentBuilder", t); } try { db.setEntityResolver(null); // setting implementation default } catch (Throwable t) { log.debug("Failed to set EntityResolver to null on DocumentBuilder", t); } } /** Get a SAX parser instance from the JAXP factory. * * @return a SAXParser instance. */ public static synchronized SAXParser getSAXParser() { if(enableParserReuse && !saxParsers.empty()) { return (SAXParser )saxParsers.pop(); } try { SAXParser parser = saxFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // parser.getParser().setEntityResolver(new DefaultEntityResolver()); // The above commented line and the following line are added // for preventing XXE (bug #14105). // We may need to uncomment the deprecated setting // in case that it is considered necessary. try { reader.setEntityResolver(DefaultEntityResolver.INSTANCE); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); return parser; } catch (ParserConfigurationException e) { log.error(Messages.getMessage("parserConfigurationException00"), e); return null; } catch (SAXException se) { log.error(Messages.getMessage("SAXException00"), se); return null; } } /** Return a SAX parser for reuse. * @param parser A SAX parser that is available for reuse */ public static void releaseSAXParser(SAXParser parser) { if(!tryReset || !enableParserReuse) return; //Free up possible ref. held by past contenthandler. try{ XMLReader xmlReader= parser.getXMLReader(); if(null != xmlReader){ xmlReader.setContentHandler(doNothingContentHandler); xmlReader.setDTDHandler(doNothingContentHandler); try { xmlReader.setEntityResolver(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } try { xmlReader.setErrorHandler(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set ErrorHandler on DocumentBuilder", t); } synchronized (XMLUtils.class ) { saxParsers.push(parser); } } else { tryReset= false; } } catch (org.xml.sax.SAXException e) { tryReset= false; } } /** * Get an empty new Document * * @return Document * @throws ParserConfigurationException if construction problems occur */ public static Document newDocument() throws ParserConfigurationException { DocumentBuilder db = null; try { db = getDocumentBuilder(); Document doc = db.newDocument(); return doc; } finally { if (db != null) { releaseDocumentBuilder(db); } } } /** * Get a new Document read from the input source * @return Document * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(InputSource inp) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db = null; try { db = getDocumentBuilder(); try { db.setEntityResolver(DefaultEntityResolver.INSTANCE); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } try { db.setErrorHandler(new XMLUtils.ParserErrorHandler()); } catch (Throwable t) { log.debug("Failed to set ErrorHandler on DocumentBuilder", t); } Document doc = db.parse(inp); return doc; } finally { if (db != null) { releaseDocumentBuilder(db); } } } /** * Get a new Document read from the input stream * @return Document * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(InputStream inp) throws ParserConfigurationException, SAXException, IOException { return XMLUtils.newDocument(new InputSource(inp)); } /** * Get a new Document read from the indicated uri * @return Document * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(String uri) throws ParserConfigurationException, SAXException, IOException { // call the authenticated version as there might be // username/password info embeded in the uri. return XMLUtils.newDocument(uri, null, null); } /** * Create a new document from the given URI, use the username and password * if the URI requires authentication. * @param uri the resource to get * @param username basic auth username * @param password basic auth password * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(String uri, String username, String password) throws ParserConfigurationException, SAXException, IOException { InputSource ins = XMLUtils.getInputSourceFromURI(uri, username, password); Document doc = XMLUtils.newDocument(ins); // Close the Stream if (ins.getByteStream() != null) { ins.getByteStream().close(); } else if (ins.getCharacterStream() != null) { ins.getCharacterStream().close(); } return doc; } private static String privateElementToString(Element element, boolean omitXMLDecl) { return DOM2Writer.nodeToString(element, omitXMLDecl); } /** * turn an element into an XML fragment * @param element * @return stringified element */ public static String ElementToString(Element element) { return privateElementToString(element, true); } /** * turn a whole DOM document into XML * @param doc DOM document * @return string representation of the document, including XML declaration */ public static String DocumentToString(Document doc) { return privateElementToString(doc.getDocumentElement(), false); } public static String PrettyDocumentToString(Document doc) { StringWriter sw = new StringWriter(); PrettyElementToWriter(doc.getDocumentElement(), sw); return sw.toString(); } public static void privateElementToWriter(Element element, Writer writer, boolean omitXMLDecl, boolean pretty) { DOM2Writer.serializeAsXML(element, writer, omitXMLDecl, pretty); } public static void ElementToStream(Element element, OutputStream out) { Writer writer = getWriter(out); privateElementToWriter(element, writer, true, false); } public static void PrettyElementToStream(Element element, OutputStream out) { Writer writer = getWriter(out); privateElementToWriter(element, writer, true, true); } public static void ElementToWriter(Element element, Writer writer) { privateElementToWriter(element, writer, true, false); } public static void PrettyElementToWriter(Element element, Writer writer) { privateElementToWriter(element, writer, true, true); } public static void DocumentToStream(Document doc, OutputStream out) { Writer writer = getWriter(out); privateElementToWriter(doc.getDocumentElement(), writer, false, false); } public static void PrettyDocumentToStream(Document doc, OutputStream out) { Writer writer = getWriter(out); privateElementToWriter(doc.getDocumentElement(), writer, false, true); } private static Writer getWriter(OutputStream os) { Writer writer = null; try { writer = new OutputStreamWriter(os, "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error(Messages.getMessage("exception00"), uee); writer = new OutputStreamWriter(os); } return writer; } public static void DocumentToWriter(Document doc, Writer writer) { privateElementToWriter(doc.getDocumentElement(), writer, false, false); } public static void PrettyDocumentToWriter(Document doc, Writer writer) { privateElementToWriter(doc.getDocumentElement(), writer, false, true); } /** * Convert a simple string to an element with a text node * * @param namespace - element namespace * @param name - element name * @param string - value of the text node * @return element - an XML Element, null if no element was created */ public static Element StringToElement(String namespace, String name, String string) { try { Document doc = XMLUtils.newDocument(); Element element = doc.createElementNS(namespace, name); Text text = doc.createTextNode(string); element.appendChild(text); return element; } catch (ParserConfigurationException e) { // This should not occur throw new InternalException(e); } } /** * get the inner XML inside an element as a string. This is done by * converting the XML to its string representation, then extracting the * subset between beginning and end tags. * @param element * @return textual body of the element, or null for no inner body */ public static String getInnerXMLString(Element element) { String elementString = ElementToString(element); int start, end; start = elementString.indexOf(">") + 1; end = elementString.lastIndexOf("</"); if (end > 0) return elementString.substring(start,end); else return null; } public static String getPrefix(String uri, Node e) { while (e != null && (e.getNodeType() == Element.ELEMENT_NODE)) { NamedNodeMap attrs = e.getAttributes(); for (int n = 0; n < attrs.getLength(); n++) { Attr a = (Attr)attrs.item(n); String name; if ((name = a.getName()).startsWith("xmlns:") && a.getNodeValue().equals(uri)) { return name.substring(6); } } e = e.getParentNode(); } return null; } /** * Searches for the namespace URI of the given prefix in the given DOM range. * * The namespace is not searched in parent of the "stopNode". This is * usefull to get all the needed namespaces when you need to ouput only a * subtree of a DOM document. * * @param prefix the prefix to find * @param e the starting node * @param stopNode null to search in all the document or a parent node where the search must stop. * @return null if no namespace is found, or the namespace URI. */ public static String getNamespace(String prefix, Node e, Node stopNode) { while (e != null && (e.getNodeType() == Node.ELEMENT_NODE)) { Attr attr = null; if (prefix == null) { attr = ((Element) e).getAttributeNode("xmlns"); } else { attr = ((Element) e).getAttributeNodeNS(Constants.NS_URI_XMLNS, prefix); } if (attr != null) return attr.getValue(); if (e == stopNode) return null; e = e.getParentNode(); } return null; } public static String getNamespace(String prefix, Node e) { return getNamespace(prefix, e, null); } /** * Return a QName when passed a string like "foo:bar" by mapping * the "foo" prefix to a namespace in the context of the given Node. * * @return a QName generated from the given string representation */ public static QName getQNameFromString(String str, Node e) { return getQNameFromString(str, e, false); } /** * Return a QName when passed a string like "foo:bar" by mapping * the "foo" prefix to a namespace in the context of the given Node. * If default namespace is found it is returned as part of the QName. * * @return a QName generated from the given string representation */ public static QName getFullQNameFromString(String str, Node e) { return getQNameFromString(str, e, true); } private static QName getQNameFromString(String str, Node e, boolean defaultNS) { if (str == null || e == null) return null; int idx = str.indexOf(':'); if (idx > -1) { String prefix = str.substring(0, idx); String ns = getNamespace(prefix, e); if (ns == null) return null; return new QName(ns, str.substring(idx + 1)); } else { if (defaultNS) { String ns = getNamespace(null, e); if (ns != null) return new QName(ns, str); } return new QName("", str); } } /** * Return a string for a particular QName, mapping a new prefix * if necessary. */ public static String getStringForQName(QName qname, Element e) { String uri = qname.getNamespaceURI(); String prefix = getPrefix(uri, e); if (prefix == null) { int i = 1; prefix = "ns" + i; while (getNamespace(prefix, e) != null) { i++; prefix = "ns" + i; } e.setAttributeNS(Constants.NS_URI_XMLNS, "xmlns:" + prefix, uri); } return prefix + ":" + qname.getLocalPart(); } /** * Concat all the text and cdata node children of this elem and return * the resulting text. * (by Matt Duftler) * * @param parentEl the element whose cdata/text node values are to * be combined. * @return the concatanated string. */ public static String getChildCharacterData (Element parentEl) { if (parentEl == null) { return null; } Node tempNode = parentEl.getFirstChild(); StringBuffer strBuf = new StringBuffer(); CharacterData charData; while (tempNode != null) { switch (tempNode.getNodeType()) { case Node.TEXT_NODE : case Node.CDATA_SECTION_NODE : charData = (CharacterData)tempNode; strBuf.append(charData.getData()); break; } tempNode = tempNode.getNextSibling(); } return strBuf.toString(); } public static class ParserErrorHandler implements ErrorHandler { protected static Log log = LogFactory.getLog(ParserErrorHandler.class.getName()); /** * Returns a string describing parse exception details */ private String getParseExceptionInfo(SAXParseException spe) { String systemId = spe.getSystemId(); if (systemId == null) { systemId = "null"; } String info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); return info; } // The following methods are standard SAX ErrorHandler methods. // See SAX documentation for more info. public void warning(SAXParseException spe) throws SAXException { if (log.isDebugEnabled()) log.debug( Messages.getMessage("warning00", getParseExceptionInfo(spe))); } public void error(SAXParseException spe) throws SAXException { String message = "Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } public void fatalError(SAXParseException spe) throws SAXException { String message = "Fatal Error: " + getParseExceptionInfo(spe); throw new SAXException(message); } } /** * Utility to get the bytes uri. * Does NOT handle authenticated URLs, * use getInputSourceFromURI(uri, username, password) * * @param uri the resource to get * @see #getInputSourceFromURI(String uri, String username, String password) */ public static InputSource getInputSourceFromURI(String uri) { return new InputSource(uri); } /** * Utility to get the bytes uri * * @param source the resource to get */ public static InputSource sourceToInputSource(Source source) { if (source instanceof SAXSource) { return ((SAXSource) source).getInputSource(); } else if (source instanceof DOMSource) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Node node = ((DOMSource)source).getNode(); if (node instanceof Document) { node = ((Document)node).getDocumentElement(); } Element domElement = (Element)node; ElementToStream(domElement, baos); InputSource isource = new InputSource(source.getSystemId()); isource.setByteStream(new ByteArrayInputStream(baos.toByteArray())); return isource; } else if (source instanceof StreamSource) { StreamSource ss = (StreamSource) source; InputSource isource = new InputSource(ss.getSystemId()); isource.setByteStream(ss.getInputStream()); isource.setCharacterStream(ss.getReader()); isource.setPublicId(ss.getPublicId()); return isource; } else { return getInputSourceFromURI(source.getSystemId()); } } /** * Utility to get the bytes at a protected uri * * This will retrieve the URL if a username and password are provided. * The java.net.URL class does not do Basic Authentication, so we have to * do it manually in this routine. * * If no username is provided, we create an InputSource from the uri * and let the InputSource go fetch the contents. * * @param uri the resource to get * @param username basic auth username * @param password basic auth password */ private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { // we can't process it, it might be a 'simple' foo.wsdl // let InputSource deal with it return new InputSource(uri); } // if no authentication, just let InputSource deal with it if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } // if this is not an HTTP{S} url, let InputSource deal with it if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); // Does this work for https??? if (!(connection instanceof HttpURLConnection)) { // can't do http with this URL, let InputSource deal with it return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(false); uconn.setUseCaches(false); // username/password info in the URL overrides passed in values String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); } public static final String base64encode(byte[] bytes) { return new String(Base64.encode(bytes)); } public static InputSource getEmptyInputSource() { return new InputSource(bais); } /** * Find a Node with a given QName * * @param node parent node * @param name QName of the child we need to find * @return child node */ public static Node findNode(Node node, QName name){ if(name.getNamespaceURI().equals(node.getNamespaceURI()) && name.getLocalPart().equals(node.getLocalName())) return node; NodeList children = node.getChildNodes(); for(int i=0;i<children.getLength();i++){ Node ret = findNode(children.item(i), name); if(ret != null) return ret; } return null; } /** * Trim all new lines from text nodes. * * @param node */ public static void normalize(Node node) { if (node.getNodeType() == Node.TEXT_NODE) { String data = ((Text) node).getData(); if (data.length() > 0) { char ch = data.charAt(data.length()-1); if(ch == '\n' || ch == '\r' || ch == ' ') { String data2 = trim(data); ((Text) node).setData(data2); } } } for (Node currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { normalize(currentChild); } } public static String trim(String str) { if (str.length() == 0) { return str; } if (str.length() == 1) { if ("\r".equals(str) || "\n".equals(str)) { return ""; } else { return str; } } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); while(lastIdx > 0) { if(last != '\n' && last != '\r' && last != ' ') break; lastIdx--; last = str.charAt(lastIdx); } if(lastIdx == 0) return ""; return str.substring(0, lastIdx); } /** * Converts a List with org.w3c.dom.Element objects to an Array * with org.w3c.dom.Element objects. * @param list List containing org.w3c.dom.Element objects * @return Element[] Array with org.w3c.dom.Element objects */ public static Element[] asElementArray(List list) { Element[] elements = new Element[list.size()]; int i = 0; Iterator detailIter = list.iterator(); while (detailIter.hasNext()) { elements[i++] = (Element) detailIter.next(); } return elements; } public static String getEncoding(Message message, MessageContext msgContext) { return getEncoding(message, msgContext, XMLEncoderFactory.getDefaultEncoder()); } public static String getEncoding(Message message, MessageContext msgContext, XMLEncoder defaultEncoder) { String encoding = null; try { if(message != null) { encoding = (String) message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); } } catch (SOAPException e) { } if(msgContext == null) { msgContext = MessageContext.getCurrentContext(); } if(msgContext != null && encoding == null){ encoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); } if (msgContext != null && encoding == null && msgContext.getAxisEngine() != null) { encoding = (String) msgContext.getAxisEngine().getOption(AxisEngine.PROP_XML_ENCODING); } if (encoding == null && defaultEncoder != null) { encoding = defaultEncoder.getEncoding(); } return encoding; } }
7,609
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/ClassUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.InputStream; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; /** * Utility methods for Class Loading. * * @author Davanum Srinvas (dims@yahoo.com) * @author Matthew Pocock (matthew_pocock@yahoo.co.uk) */ public final class ClassUtils { /** default class loader */ private static ClassLoader defaultClassLoader = ClassUtils.class.getClassLoader(); /** * Set the default ClassLoader. If loader is null, the default loader is * not changed. * * @param loader the new default ClassLoader */ public static void setDefaultClassLoader(ClassLoader loader) { if (loader != null) defaultClassLoader = loader; } public static ClassLoader getDefaultClassLoader() { return defaultClassLoader; } /** * Use this method instead of Class.forName * * @param className Class name * @return java class * @throws ClassNotFoundException if the class is not found */ public static Class forName(String className) throws ClassNotFoundException { return loadClass(className); } /** * Use this method instead of Class.forName (String className, boolean init, ClassLoader loader) * * @param _className Class name * @param init initialize the class * @param _loader class loader * @return java class * * @throws ClassNotFoundException if the class is not found */ public static Class forName( String _className, boolean init, ClassLoader _loader) throws ClassNotFoundException { // Create final vars for doPrivileged block final String className = _className; final ClassLoader loader = _loader; try { // Get the class within a doPrivleged block Object ret = AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { return Class.forName(className, true, loader); } catch (Throwable e) { return e; } } }); // If the class was located, return it. Otherwise throw exception if (ret instanceof Class) { return (Class) ret; } else if (ret instanceof ClassNotFoundException) { throw (ClassNotFoundException) ret; } else { throw new ClassNotFoundException(_className); } } catch (ClassNotFoundException cnfe) { return loadClass(className); } } /** * Loads the class from the context class loader and then falls back to * getDefaultClassLoader().forName * * @param _className Class name * @return java class * @throws ClassNotFoundException if the class is not found */ private static Class loadClass(String _className) throws ClassNotFoundException { // Create final vars for doPrivileged block final String className = _className; // Get the class within a doPrivleged block Object ret = AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { // Try the context class loader ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return Class.forName(className, true, classLoader); } catch (ClassNotFoundException cnfe2) { try { // Try the classloader that loaded this class. ClassLoader classLoader = ClassUtils.class.getClassLoader(); return Class.forName(className, true, classLoader); } catch (ClassNotFoundException cnfe3) { // Try the default class loader. try { return defaultClassLoader.loadClass( className); } catch (Throwable e) { // Still not found, return exception return e; } } } } }); // If the class was located, return it. Otherwise throw exception if (ret instanceof Class) { return (Class) ret; } else if (ret instanceof ClassNotFoundException) { throw (ClassNotFoundException) ret; } else { throw new ClassNotFoundException(_className); } } /** * Get an input stream from a named resource. * Tries * <ol> * <li>the thread context class loader * <li>the given fallback classloader * <li>the system classloader * </ol> * @param resource resource string to look for * @param fallbackClassLoader the class loader to use if the resource could not be loaded from * the thread context class loader * @return input stream if found, or null */ public static InputStream getResourceAsStream(String resource, ClassLoader fallbackClassLoader) { InputStream is = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); if (tccl != null) { // try the context class loader. is = tccl.getResourceAsStream(resource); } if (is == null) { // if not found in context class loader fall back to default if (fallbackClassLoader != null) { is = fallbackClassLoader.getResourceAsStream(resource); } else { // Try the system class loader. is = ClassLoader.getSystemClassLoader().getResourceAsStream(resource); } } return is; } /** * Get an input stream from a named resource. * Tries * <ol> * <li>the classloader that loaded "clazz" first, * <li>the system classloader * <li>the class "clazz" itself * </ol> * @param clazz class to use in the lookups * @param resource resource string to look for * @return input stream if found, or null */ public static InputStream getResourceAsStream(Class clazz, String resource) { InputStream myInputStream = null; if(clazz.getClassLoader()!=null) { // Try the class loader that loaded this class. myInputStream = clazz.getClassLoader().getResourceAsStream(resource); } else { // Try the system class loader. myInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resource); } if (myInputStream == null && Thread.currentThread().getContextClassLoader() != null) { // try the context class loader. myInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); } if (myInputStream == null) { // if not found in classpath fall back to default myInputStream = clazz.getResourceAsStream(resource); } return myInputStream; } /** * Creates a new ClassLoader from a classpath specification and a parent * class loader. * The classpath string will be split using the system path seperator * character (e.g. : or ;), just as the java system-wide class path is * processed. * * @param classpath the classpath String * @param parent the parent ClassLoader, or null if the default is to be * used * @throws SecurityException if you don't have privilages to create * class loaders * @throws IllegalArgumentException if your classpath string is silly */ public static ClassLoader createClassLoader(String classpath, ClassLoader parent) throws SecurityException { String[] names = StringUtils.split(classpath, System.getProperty("path.separator").charAt(0)); URL[] urls = new URL[names.length]; try { for(int i = 0; i < urls.length; i++) urls[i] = new File(names[i]).toURL(); } catch (MalformedURLException e) { // I don't think this is possible, so I'm throwing this as an // un-checked exception throw (IllegalArgumentException) new IllegalArgumentException( "Unable to parse classpath: " + classpath); } return new URLClassLoader(urls, parent); } }
7,610
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/NSStack.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.ArrayList; /** * The abstraction this class provides is a push down stack of variable * length frames of prefix to namespace mappings. Used for keeping track * of what namespaces are active at any given point as an XML document is * traversed or produced. * * From a performance point of view, this data will both be modified frequently * (at a minimum, there will be one push and pop per XML element processed), * and scanned frequently (many of the "good" mappings will be at the bottom * of the stack). The one saving grace is that the expected maximum * cardinalities of the number of frames and the number of total mappings * is only in the dozens, representing the nesting depth of an XML document * and the number of active namespaces at any point in the processing. * * Accordingly, this stack is implemented as a single array, will null * values used to indicate frame boundaries. * * @author James Snell * @author Glen Daniels (gdaniels@apache.org) * @author Sam Ruby (rubys@us.ibm.com) */ public class NSStack { protected static Log log = LogFactory.getLog(NSStack.class.getName()); private Mapping[] stack; private int top = 0; private int iterator = 0; private int currentDefaultNS = -1; private boolean optimizePrefixes = true; // invariant member variable to track low-level logging requirements // we cache this once per instance lifecycle to avoid repeated lookups // in heavily used code. private final boolean traceEnabled = log.isTraceEnabled(); public NSStack(boolean optimizePrefixes) { this.optimizePrefixes = optimizePrefixes; stack = new Mapping[32]; stack[0] = null; } public NSStack() { stack = new Mapping[32]; stack[0] = null; } /** * Create a new frame at the top of the stack. */ public void push() { top ++; if (top >= stack.length) { Mapping newstack[] = new Mapping[stack.length*2]; System.arraycopy (stack, 0, newstack, 0, stack.length); stack = newstack; } if (traceEnabled) log.trace("NSPush (" + stack.length + ")"); stack[top] = null; } /** * Remove the top frame from the stack. */ public void pop() { clearFrame(); top--; // If we've moved below the current default NS, figure out the new // default (if any) if (top < currentDefaultNS) { // Reset the currentDefaultNS to ignore the frame just removed. currentDefaultNS = top; while (currentDefaultNS > 0) { if (stack[currentDefaultNS] != null && stack[currentDefaultNS].getPrefix().length() == 0) break; currentDefaultNS--; } } if (top == 0) { if (traceEnabled) log.trace("NSPop (" + Messages.getMessage("empty00") + ")"); return; } if (traceEnabled){ log.trace("NSPop (" + stack.length + ")"); } } /** * Return a copy of the current frame. Returns null if none are present. */ public ArrayList cloneFrame() { if (stack[top] == null) return null; ArrayList clone = new ArrayList(); for (Mapping map=topOfFrame(); map!=null; map=next()) { clone.add(map); } return clone; } /** * Remove all mappings from the current frame. */ private void clearFrame() { while (stack[top] != null) top--; } /** * Reset the embedded iterator in this class to the top of the current * (i.e., last) frame. Note that this is not threadsafe, nor does it * provide multiple iterators, so don't use this recursively. Nor * should you modify the stack while iterating over it. */ public Mapping topOfFrame() { iterator = top; while (stack[iterator] != null) iterator--; iterator++; return next(); } /** * Return the next namespace mapping in the top frame. */ public Mapping next() { if (iterator > top) { return null; } else { return stack[iterator++]; } } /** * Add a mapping for a namespaceURI to the specified prefix to the top * frame in the stack. If the prefix is already mapped in that frame, * remap it to the (possibly different) namespaceURI. */ public void add(String namespaceURI, String prefix) { int idx = top; prefix = prefix.intern(); try { // Replace duplicate prefixes (last wins - this could also fault) for (int cursor=top; stack[cursor]!=null; cursor--) { if (stack[cursor].getPrefix() == prefix) { stack[cursor].setNamespaceURI(namespaceURI); idx = cursor; return; } } push(); stack[top] = new Mapping(namespaceURI, prefix); idx = top; } finally { // If this is the default namespace, note the new in-scope // default is here. if (prefix.length() == 0) { currentDefaultNS = idx; } } } /** * Return an active prefix for the given namespaceURI. NOTE : This * may return null even if the namespaceURI was actually mapped further * up the stack IF the prefix which was used has been repeated further * down the stack. I.e.: * * <pre> * &lt;pre:outer xmlns:pre="namespace"&gt; * &lt;pre:inner xmlns:pre="otherNamespace"&gt; * *here's where we're looking* * &lt;/pre:inner&gt; * &lt;/pre:outer&gt; * </pre> * * If we look for a prefix for "namespace" at the indicated spot, we won't * find one because "pre" is actually mapped to "otherNamespace" */ public String getPrefix(String namespaceURI, boolean noDefault) { if ((namespaceURI == null) || (namespaceURI.length()==0)) return null; if(optimizePrefixes) { // If defaults are OK, and the given NS is the current default, // return "" as the prefix to favor defaults where possible. if (!noDefault && currentDefaultNS > 0 && stack[currentDefaultNS] != null && namespaceURI == stack[currentDefaultNS].getNamespaceURI()) return ""; } namespaceURI = namespaceURI.intern(); for (int cursor=top; cursor>0; cursor--) { Mapping map = stack[cursor]; if (map == null) continue; if (map.getNamespaceURI() == namespaceURI) { String possiblePrefix = map.getPrefix(); if (noDefault && possiblePrefix.length() == 0) continue; // now make sure that this is the first occurance of this // particular prefix for (int cursor2 = top; true; cursor2--) { if (cursor2 == cursor) return possiblePrefix; map = stack[cursor2]; if (map == null) continue; if (possiblePrefix == map.getPrefix()) break; } } } return null; } /** * Return an active prefix for the given namespaceURI, including * the default prefix (""). */ public String getPrefix(String namespaceURI) { return getPrefix(namespaceURI, false); } /** * Given a prefix, return the associated namespace (if any). */ public String getNamespaceURI(String prefix) { if (prefix == null) prefix = ""; prefix = prefix.intern(); for (int cursor=top; cursor>0; cursor--) { Mapping map = stack[cursor]; if (map == null) continue; if (map.getPrefix() == prefix) return map.getNamespaceURI(); } return null; } /** * Produce a trace dump of the entire stack, starting from the top and * including frame markers. */ public void dump(String dumpPrefix) { for (int cursor=top; cursor>0; cursor--) { Mapping map = stack[cursor]; if (map == null) { log.trace(dumpPrefix + Messages.getMessage("stackFrame00")); } else { log.trace(dumpPrefix + map.getNamespaceURI() + " -> " + map.getPrefix()); } } } }
7,611
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/BeanPropertyDescriptor.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.beans.IndexedPropertyDescriptor; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; /** * This class represents a field/property in a value type (a class with either * bean-style getters/setters or public fields). * * It is essentially a thin wrapper around the PropertyDescriptor from the * JavaBean utilities. We wrap it with this class so that we can create * the subclass FieldPropertyDescriptor and access public fields (who * wouldn't have PropertyDescriptors normally) via the same interface. * * There are also some interesting tricks where indexed properties are * concerned, mostly involving the fact that we manage the arrays here * rather than relying on the value type class to do it itself. * * @author Rich Scheuerle (scheu@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) **/ public class BeanPropertyDescriptor { protected static Log log = LogFactory.getLog(BeanPropertyDescriptor.class.getName()); protected PropertyDescriptor myPD = null; protected static final Object[] noArgs = new Object[] {}; /** * Constructor (takes a PropertyDescriptor) * * @param pd */ public BeanPropertyDescriptor(PropertyDescriptor pd) { myPD = pd; } /** * Protected constructor for use by our children */ protected BeanPropertyDescriptor() { } /** * Get our property name. */ public String getName(){ return myPD.getName(); } /** * Query if property is readable * @return true if readable */ public boolean isReadable() { return (myPD.getReadMethod() != null); } /** * Query if property is writeable * @return true if writeable */ public boolean isWriteable() { return (myPD.getWriteMethod() != null); } /** * Query if property is indexed * * @return true if indexed methods exist */ public boolean isIndexed() { return (myPD instanceof IndexedPropertyDescriptor); } /** * Query if property is indexed or if it' an array. * * @return true if indexed methods exist or if it's an array */ public boolean isIndexedOrArray() { return (isIndexed() || isArray()); } /** * Query if property is an array (excluded byte[]). * @return true if it's an array (excluded byte[]) */ public boolean isArray() { return ((myPD.getPropertyType() != null) && myPD.getPropertyType() .isArray()); } /** * Get the property value * @param obj is the object * @return the entire propery value */ public Object get(Object obj) throws InvocationTargetException, IllegalAccessException { Method readMethod = myPD.getReadMethod(); if (readMethod != null) { return readMethod.invoke(obj, noArgs); } else { throw new IllegalAccessException(Messages.getMessage("badGetter00")); } } /** * Set the property value * @param obj is the object * @param newValue is the new value */ public void set(Object obj, Object newValue) throws InvocationTargetException, IllegalAccessException { Method writeMethod = myPD.getWriteMethod(); if (writeMethod != null) { writeMethod.invoke(obj, new Object[] {newValue}); } else { throw new IllegalAccessException(Messages.getMessage("badSetter00")); } } /** * Get an indexed property * @param obj is the object * @param i the index * @return the object at the indicated index */ public Object get(Object obj, int i) throws InvocationTargetException, IllegalAccessException { if (!isIndexed()) { return Array.get(get(obj), i); } else { IndexedPropertyDescriptor id = (IndexedPropertyDescriptor)myPD; return id.getIndexedReadMethod().invoke(obj, new Object[] { new Integer(i)}); } } /** * Set an indexed property value * @param obj is the object * @param i the index * @param newValue is the new value */ public void set(Object obj, int i, Object newValue) throws InvocationTargetException, IllegalAccessException { // Set the new value if (isIndexed()) { IndexedPropertyDescriptor id = (IndexedPropertyDescriptor)myPD; growArrayToSize(obj, id.getIndexedPropertyType(), i); id.getIndexedWriteMethod().invoke(obj, new Object[] { new Integer(i), newValue}); } else { // Not calling 'growArrayToSize' to avoid an extra call to the // property's setter. The setter will be called at the end anyway. // growArrayToSize(obj, myPD.getPropertyType().getComponentType(), i); Object array = get(obj); if (array == null || Array.getLength(array) <= i) { Class componentType = getType().getComponentType(); Object newArray = Array.newInstance(componentType, i + 1); // Copy over the old elements if (array != null) { System.arraycopy(array, 0, newArray, 0, Array.getLength(array)); } array = newArray; } Array.set(array, i, newValue); // Fix for non-indempondent array-type propertirs. // Make sure we call the property's setter. set(obj, array); } } /** * Grow the array * @param obj * @param componentType * @param i * @throws InvocationTargetException * @throws IllegalAccessException */ protected void growArrayToSize(Object obj, Class componentType, int i) throws InvocationTargetException, IllegalAccessException { // Get the entire array and make sure it is large enough Object array = get(obj); if (array == null || Array.getLength(array) <= i) { // Construct a larger array of the same type Object newArray = Array.newInstance(componentType, i + 1); // Copy over the old elements if (array != null) { System.arraycopy(array, 0, newArray, 0, Array.getLength(array)); } // Set the object to use the larger array set(obj, newArray); } } /** * Get the type of a property * @return the type of the property */ public Class getType() { if (isIndexed()) { return ((IndexedPropertyDescriptor)myPD).getIndexedPropertyType(); } else { return myPD.getPropertyType(); } } public Class getActualType() { return myPD.getPropertyType(); } }
7,612
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/WSDLUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import javax.wsdl.Port; import javax.wsdl.extensions.soap.SOAPAddress; import javax.wsdl.extensions.soap12.SOAP12Address; import java.util.List; import java.util.ListIterator; public class WSDLUtils { protected static Log log = LogFactory.getLog(WSDLUtils.class.getName()); /** * Return the endpoint address from a &lt;soap:address location="..."&gt; tag */ public static String getAddressFromPort(Port p) { // Get the endpoint for a port List extensibilityList = p.getExtensibilityElements(); for (ListIterator li = extensibilityList.listIterator(); li.hasNext();) { Object obj = li.next(); if (obj instanceof SOAPAddress) { return ((SOAPAddress) obj).getLocationURI(); } else if (obj instanceof SOAP12Address){ return ((SOAP12Address) obj).getLocationURI(); } } // didn't find it return null; } // getAddressFromPort } // class WSDLUtils
7,613
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/LockableHashtable.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils ; import java.util.Hashtable; import java.util.Vector; import java.util.Set; import java.util.HashSet; // fixme: Is there a reason to use Hashtable rather than Map here? /** * This subclass of the java Hashtable allows individual * entries to be "locked" so that their values cannot be * overwritten or removed. * * Note, only the put() and remove() methods have been * overridden. The clear() method still removes all * entries whether they've been locked or not. * * @author James Snell (jasnell@us.ibm.com) */ public class LockableHashtable extends Hashtable { // fixme - we are potentialy synchronizing on /both/ the current Hashtable // and also the Vector - a non-synchronizing List impl such as ArrayList // may give better performance. We are doing lots of .contains on this // Vector - it would probably be better to use a Set impl /** * Stores the keys of the locked entries */ Vector lockedEntries; /** Place to look for properties which we don't find locally. */ private Hashtable parent = null; public LockableHashtable() { super(); } public LockableHashtable(int p1, float p2) { super(p1, p2); } public LockableHashtable(java.util.Map p1) { super(p1); } public LockableHashtable(int p1) { super(p1); } /** * Set the parent Hashtable for this object */ public synchronized void setParent(Hashtable parent) { this.parent = parent; } /** * Gets the parent Hashtable for this object (if any) */ public synchronized Hashtable getParent() { return parent; } /** * Returns the keys in this hashtable, and its parent chain */ public Set getAllKeys() { HashSet set = new HashSet(); set.addAll(super.keySet()); Hashtable p = parent; while (p != null) { set.addAll(p.keySet()); if (p instanceof LockableHashtable) { p = ((LockableHashtable) p).getParent(); } else { p = null; } } return set; } /** * Get an entry from this hashtable, and if we don't find anything, * defer to our parent, if any. */ public synchronized Object get(Object key) { Object ret = super.get(key); if ((ret == null) && (parent != null)) { ret = parent.get(key); } return ret; } /** * New version of the put() method that allows for explicitly marking * items added to the hashtable as locked. */ public synchronized Object put(Object p1, Object p2, boolean locked) { if (lockedEntries != null && this.containsKey(p1) && lockedEntries.contains(p1)) { return null; } if (locked) { if (lockedEntries == null) { lockedEntries = new Vector(); } lockedEntries.add(p1); } return super.put(p1, p2); } /** * Overrides the Hashtable.put() method to mark items as not being locked. */ public synchronized Object put(Object p1, Object p2) { return put(p1, p2, false); } /** * Checks to see if an item is locked before it is removed. */ public synchronized Object remove(Object p1) { if (lockedEntries != null && lockedEntries.contains(p1)) { return null; } return super.remove(p1); } /** * Returns true if a given key is in our locked list */ public boolean isKeyLocked(Object key) { return lockedEntries != null && lockedEntries.contains(key); } }
7,614
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/DefaultErrorHandler.java
/* * 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.axis.utils; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Default {@link ErrorHandler} implementation. The implementation is identical to * {@link DefaultHandler}, i.e. {@link ErrorHandler#fatalError(SAXParseException)} throws the * exception passed as parameter, while the other methods do nothing. * * @author Andreas Veithen */ public class DefaultErrorHandler implements ErrorHandler { /** * The singleton instance. */ public static final DefaultErrorHandler INSTANCE = new DefaultErrorHandler(); private DefaultErrorHandler() {} public void warning(SAXParseException exception) throws SAXException { } public void error(SAXParseException exception) throws SAXException { } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } }
7,615
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/Mapping.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.Serializable; /** * this class represents a mapping from namespace to prefix */ public class Mapping implements Serializable { private String namespaceURI; private String prefix; public Mapping (String namespaceURI, String prefix) { setPrefix(prefix); setNamespaceURI(namespaceURI); } public String getNamespaceURI() { return namespaceURI; } public void setNamespaceURI (String namespaceURI) { this.namespaceURI = namespaceURI.intern(); } public String getPrefix() { return prefix; } public void setPrefix (String prefix) { this.prefix = prefix.intern(); } }
7,616
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/DefaultAuthenticator.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.components.net.TransportClientProperties; import org.apache.axis.components.net.TransportClientPropertiesFactory; /** * This class is used by WSDL2javaAntTask and WSDL2. * Supports the http.proxyUser and http.proxyPassword properties. */ public class DefaultAuthenticator extends java.net.Authenticator { private TransportClientProperties tcp = null; private String user; private String password; public DefaultAuthenticator(String user, String pass) { this.user = user; this.password = pass; } protected java.net.PasswordAuthentication getPasswordAuthentication() { // if user and password weren't provided, check the system properties if (user == null) { user = getTransportClientProperties().getProxyUser(); } if (password == null) { password = getTransportClientProperties().getProxyPassword(); } return new java.net.PasswordAuthentication(user, password.toCharArray()); } private TransportClientProperties getTransportClientProperties() { if (tcp == null) { tcp = TransportClientPropertiesFactory.create("http"); } return tcp; } }
7,617
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/FieldPropertyDescriptor.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /** * * @author Glen Daniels (gdaniels@apache.org) */ public class FieldPropertyDescriptor extends BeanPropertyDescriptor { private Field field = null; /** * Construct a BPD with a field * Both must be set * @param _name is the name of the property * @param _field is the name of the public instance field */ public FieldPropertyDescriptor(String _name, Field _field) { field = _field; try { myPD = new PropertyDescriptor(_name, null, null); } catch (Exception e) { // ??? } if (_field == null || _name == null) { throw new IllegalArgumentException( Messages.getMessage(_field == null ? "badField00" : "badProp03")); } } public String getName() { return field.getName(); } /** * Query if property is readable * @return true if readable */ public boolean isReadable() { return true; } /** * Query if property is writeable * @return true if writeable */ public boolean isWriteable() { return true; } /** * Query if property is indexed. * Indexed properties require valid setters/getters * @return true if indexed methods exist */ public boolean isIndexed() { return (field.getType().getComponentType() != null); } /** * Get the property value * @param obj is the object * @return the entire propery value */ public Object get(Object obj) throws InvocationTargetException, IllegalAccessException { return field.get(obj); } /** * Set the property value * @param obj is the object * @param newValue is the new value */ public void set(Object obj, Object newValue) throws InvocationTargetException, IllegalAccessException { field.set(obj, newValue); } /** * Get an indexed property * @param obj is the object * @param i the index * @return the object at the indicated index */ public Object get(Object obj, int i) throws InvocationTargetException, IllegalAccessException { if (!isIndexed()) { throw new IllegalAccessException("Not an indexed property"); } Object array = field.get(obj); return Array.get(array, i); } /** * Set an indexed property value * @param obj is the object * @param i the index * @param newValue is the new value */ public void set(Object obj, int i, Object newValue) throws InvocationTargetException, IllegalAccessException { if (!isIndexed()) { throw new IllegalAccessException("Not an indexed field!"); } Class componentType = field.getType().getComponentType(); growArrayToSize(obj, componentType, i); Array.set(get(obj), i, newValue); } /** * Get the type of a property * @return the type of the property */ public Class getType() { if (isIndexed()) { return field.getType().getComponentType(); } else { return field.getType(); } } public Class getActualType() { return field.getType(); } public Field getField() { return field; } }
7,618
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/TeeOutputStream.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.OutputStream; import java.io.IOException; public class TeeOutputStream extends OutputStream { private OutputStream left; private OutputStream right; public TeeOutputStream(OutputStream left, OutputStream right) { this.left = left; this.right = right; } public void close() throws IOException { left.close(); right.close(); } public void flush() throws IOException { left.flush(); right.flush(); } public void write(byte[] b) throws IOException { left.write(b); right.write(b); } public void write(byte[] b, int off, int len) throws IOException { left.write(b, off, len); right.write(b, off, len); } public void write(int b) throws IOException { left.write(b); right.write(b); } }
7,619
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/JavaUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.attachments.AttachmentPart; import org.apache.axis.attachments.OctetStream; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.types.HexBinary; import org.apache.commons.logging.Log; import javax.activation.DataHandler; import javax.imageio.ImageIO; import javax.xml.soap.SOAPException; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import java.awt.*; import java.beans.Introspector; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.WeakHashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; /** Utility class to deal with Java language related issues, such * as type conversions. * * @author Glen Daniels (gdaniels@apache.org) */ public class JavaUtils { private JavaUtils() { } protected static Log log = LogFactory.getLog(JavaUtils.class.getName()); public static final char NL = '\n'; public static final char CR = '\r'; /** * The prefered line separator */ public static final String LS = System.getProperty("line.separator", (new Character(NL)).toString()); public static Class getWrapperClass(Class primitive) { if (primitive == int.class) return java.lang.Integer.class; else if (primitive == short.class) return java.lang.Short.class; else if (primitive == boolean.class) return java.lang.Boolean.class; else if (primitive == byte.class) return java.lang.Byte.class; else if (primitive == long.class) return java.lang.Long.class; else if (primitive == double.class) return java.lang.Double.class; else if (primitive == float.class) return java.lang.Float.class; else if (primitive == char.class) return java.lang.Character.class; return null; } public static String getWrapper(String primitive) { if (primitive.equals("int")) return "Integer"; else if (primitive.equals("short")) return "Short"; else if (primitive.equals("boolean")) return "Boolean"; else if (primitive.equals("byte")) return "Byte"; else if (primitive.equals("long")) return "Long"; else if (primitive.equals("double")) return "Double"; else if (primitive.equals("float")) return "Float"; else if (primitive.equals("char")) return "Character"; return null; } public static Class getPrimitiveClass(Class wrapper) { if (wrapper == java.lang.Integer.class) return int.class; else if (wrapper == java.lang.Short.class) return short.class; else if (wrapper == java.lang.Boolean.class) return boolean.class; else if (wrapper == java.lang.Byte.class) return byte.class; else if (wrapper == java.lang.Long.class) return long.class; else if (wrapper == java.lang.Double.class) return double.class; else if (wrapper == java.lang.Float.class) return float.class; else if (wrapper == java.lang.Character.class) return char.class; return null; } public static Class getPrimitiveClassFromName(String primitive) { if (primitive.equals("int")) return int.class; else if (primitive.equals("short")) return short.class; else if (primitive.equals("boolean")) return boolean.class; else if (primitive.equals("byte")) return byte.class; else if (primitive.equals("long")) return long.class; else if (primitive.equals("double")) return double.class; else if (primitive.equals("float")) return float.class; else if (primitive.equals("char")) return char.class; return null; } /* * Any builtin type that has a constructor that takes a String is a basic * type. * This is for optimization purposes, so that we don't introspect * primitive java types or some basic Axis types. */ public static boolean isBasic(Class javaType) { return (javaType.isPrimitive() || javaType == String.class || javaType == Boolean.class || javaType == Float.class || javaType == Double.class || Number.class.isAssignableFrom(javaType) || javaType == org.apache.axis.types.Day.class || javaType == org.apache.axis.types.Duration.class || javaType == org.apache.axis.types.Entities.class || javaType == org.apache.axis.types.Entity.class || javaType == HexBinary.class || javaType == org.apache.axis.types.Id.class || javaType == org.apache.axis.types.IDRef.class || javaType == org.apache.axis.types.IDRefs.class || javaType == org.apache.axis.types.Language.class || javaType == org.apache.axis.types.Month.class || javaType == org.apache.axis.types.MonthDay.class || javaType == org.apache.axis.types.Name.class || javaType == org.apache.axis.types.NCName.class || javaType == org.apache.axis.types.NegativeInteger.class || javaType == org.apache.axis.types.NMToken.class || javaType == org.apache.axis.types.NMTokens.class || javaType == org.apache.axis.types.NonNegativeInteger.class || javaType == org.apache.axis.types.NonPositiveInteger.class || javaType == org.apache.axis.types.NormalizedString.class || javaType == org.apache.axis.types.PositiveInteger.class || javaType == org.apache.axis.types.Time.class || javaType == org.apache.axis.types.Token.class || javaType == org.apache.axis.types.UnsignedByte.class || javaType == org.apache.axis.types.UnsignedInt.class || javaType == org.apache.axis.types.UnsignedLong.class || javaType == org.apache.axis.types.UnsignedShort.class || javaType == org.apache.axis.types.URI.class || javaType == org.apache.axis.types.Year.class || javaType == org.apache.axis.types.YearMonth.class); } /** * It the argument to the convert(...) method implements * the ConvertCache interface, the convert(...) method * will use the set/get methods to store and retrieve * converted values. **/ public interface ConvertCache { /** * Set/Get converted values of the convert method. **/ public void setConvertedValue(Class cls, Object value); public Object getConvertedValue(Class cls); /** * Get the destination array class described by the xml **/ public Class getDestClass(); } /** Utility function to convert an Object to some desired Class. * * Right now this works for: * arrays &lt;-&gt; Lists, * Holders &lt;-&gt; held values * @param arg the array to convert * @param destClass the actual class we want */ public static Object convert(Object arg, Class destClass) { if (destClass == null) { return arg; } Class argHeldType = null; if (arg != null) { argHeldType = getHolderValueType(arg.getClass()); } if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) { return arg; } if (log.isDebugEnabled()) { String clsName = "null"; if (arg != null) clsName = arg.getClass().getName(); log.debug( Messages.getMessage("convert00", clsName, destClass.getName())); } // See if a previously converted value is stored in the argument. Object destValue = null; if (arg instanceof ConvertCache) { destValue = (( ConvertCache) arg).getConvertedValue(destClass); if (destValue != null) return destValue; } // Get the destination held type or the argument held type if they exist Class destHeldType = getHolderValueType(destClass); // Convert between Axis special purpose HexBinary and byte[] if (arg instanceof HexBinary && destClass == byte[].class) { return ((HexBinary) arg).getBytes(); } else if (arg instanceof byte[] && destClass == HexBinary.class) { return new HexBinary((byte[]) arg); } // Convert between Calendar and Date if (arg instanceof Calendar && destClass == Date.class) { return ((Calendar) arg).getTime(); } if (arg instanceof Date && destClass == Calendar.class) { Calendar calendar = Calendar.getInstance(); calendar.setTime((Date) arg); return calendar; } // Convert between Calendar and java.sql.Date if (arg instanceof Calendar && destClass == java.sql.Date.class) { return new java.sql.Date(((Calendar) arg).getTime().getTime()); } // Convert between HashMap and Hashtable if (arg instanceof HashMap && destClass == Hashtable.class) { return new Hashtable((HashMap)arg); } // Convert an AttachmentPart to the given destination class. if (isAttachmentSupported() && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) { try { String destName = destClass.getName(); if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class || destName.equals("javax.mail.internet.MimeMultipart")) { DataHandler handler = null; if (arg instanceof AttachmentPart) { handler = ((AttachmentPart) arg).getDataHandler(); } else if (arg instanceof DataHandler) { handler = (DataHandler) arg; } if (destClass == Image.class) { // Note: An ImageIO component is required to process an Image // attachment, but if the image would be null // (is.available == 0) then ImageIO component isn't needed // and we can return null. InputStream is = handler.getInputStream(); if (is.available() == 0) { return null; } else { return ImageIO.read(is); } } else if (destClass == javax.xml.transform.Source.class) { // For a reason unknown to me, the handler's // content is a String. Convert it to a // StreamSource. return new StreamSource(handler.getInputStream()); } else if (destClass == OctetStream.class || destClass == byte[].class) { InputStream in = null; if (arg instanceof InputStream) { in = (InputStream) arg; } else { in = handler.getInputStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); int byte1 = -1; while((byte1 = in.read())!=-1) baos.write(byte1); return new OctetStream(baos.toByteArray()); } else if (destClass == DataHandler.class) { return handler; } else { return handler.getContent(); } } } catch (IOException ioe) { } catch (SOAPException se) { } } // If the destination is an array and the source // is a suitable component, return an array with // the single item. if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class) && destClass.getComponentType().isAssignableFrom(arg.getClass())) { Object array = Array.newInstance(destClass.getComponentType(), 1); Array.set(array, 0, arg); return array; } // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[]) if (arg != null && destClass.isArray()) { Object newArg = ArrayUtil.convertObjectToArray(arg, destClass); if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) { return newArg; } } // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT) if (arg != null && arg.getClass().isArray()) { Object newArg = ArrayUtil.convertArrayToObject(arg, destClass); if (newArg != null) return newArg; } // Return if no conversion is available if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray())) && ((destHeldType == null && argHeldType == null) || (destHeldType != null && argHeldType != null))) { return arg; } // Take care of Holder conversion if (destHeldType != null) { // Convert arg into Holder holding arg. Object newArg = convert(arg, destHeldType); Object argHolder = null; try { argHolder = destClass.newInstance(); setHolderValue(argHolder, newArg); return argHolder; } catch (Exception e) { return arg; } } else if (argHeldType != null) { // Convert arg into the held type try { Object newArg = getHolderValue(arg); return convert(newArg, destClass); } catch (HolderException e) { return arg; } } // Flow to here indicates that neither arg or destClass is a Holder // Check to see if the argument has a prefered destination class. if (arg instanceof ConvertCache && (( ConvertCache) arg).getDestClass() != destClass) { Class hintClass = ((ConvertCache) arg).getDestClass(); if (hintClass != null && hintClass.isArray() && destClass.isArray() && destClass.isAssignableFrom(hintClass)) { destClass = hintClass; destValue = ((ConvertCache) arg).getConvertedValue(destClass); if (destValue != null) return destValue; } } if (arg == null) { return arg; } // The arg may be an array or List int length = 0; if (arg.getClass().isArray()) { length = Array.getLength(arg); } else { length = ((Collection) arg).size(); } if (destClass.isArray()) { if (destClass.getComponentType().isPrimitive()) { Object array = Array.newInstance(destClass.getComponentType(), length); // Assign array elements if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { Array.set(array, i, Array.get(arg, i)); } } else { int idx = 0; for (Iterator i = ((Collection)arg).iterator(); i.hasNext();) { Array.set(array, idx++, i.next()); } } destValue = array; } else { Object [] array; try { array = (Object [])Array.newInstance(destClass.getComponentType(), length); } catch (Exception e) { return arg; } // Use convert to assign array elements. if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { array[i] = convert(Array.get(arg, i), destClass.getComponentType()); } } else { int idx = 0; for (Iterator i = ((Collection)arg).iterator(); i.hasNext();) { array[idx++] = convert(i.next(), destClass.getComponentType()); } } destValue = array; } } else if (Collection.class.isAssignableFrom(destClass)) { Collection newList = null; try { // if we are trying to create an interface, build something // that implements the interface if (destClass == Collection.class || destClass == List.class) { newList = new ArrayList(); } else if (destClass == Set.class) { newList = new HashSet(); } else { newList = (Collection)destClass.newInstance(); } } catch (Exception e) { // Couldn't build one for some reason... so forget it. return arg; } if (arg.getClass().isArray()) { for (int j = 0; j < length; j++) { newList.add(Array.get(arg, j)); } } else { for (Iterator j = ((Collection)arg).iterator(); j.hasNext();) { newList.add(j.next()); } } destValue = newList; } else { destValue = arg; } // Store the converted value in the argument if possible. if (arg instanceof ConvertCache) { (( ConvertCache) arg).setConvertedValue(destClass, destValue); } return destValue; } public static boolean isConvertable(Object obj, Class dest) { return isConvertable(obj, dest, false); } public static boolean isConvertable(Object obj, Class dest, boolean isEncoded) { Class src = null; if (obj != null) { if (obj instanceof Class) { src = (Class)obj; } else { src = obj.getClass(); } } else { if(!dest.isPrimitive()) return true; } if (dest == null) return false; if (src != null) { // If we're directly assignable, we're good. if (dest.isAssignableFrom(src)) return true; //Allow mapping of Map's to Map's if (java.util.Map.class.isAssignableFrom(dest) && java.util.Map.class.isAssignableFrom(src)) { return true; } // If it's a wrapping conversion, we're good. if (getWrapperClass(src) == dest) return true; if (getWrapperClass(dest) == src) return true; // If it's List -> Array or vice versa, we're good. if ((Collection.class.isAssignableFrom(src) || src.isArray()) && (Collection.class.isAssignableFrom(dest) || dest.isArray()) && (src.getComponentType() == Object.class || src.getComponentType() == null || dest.getComponentType() == Object.class || dest.getComponentType() == null || isConvertable(src.getComponentType(), dest.getComponentType()))) return true; // If destination is an array, and src is a component, we're good // if we're not encoded! if (!isEncoded && dest.isArray() && // !dest.getComponentType().equals(Object.class) && dest.getComponentType().isAssignableFrom(src)) return true; if ((src == HexBinary.class && dest == byte[].class) || (src == byte[].class && dest == HexBinary.class)) return true; // Allow mapping of Calendar to Date if (Calendar.class.isAssignableFrom(src) && dest == Date.class) return true; // Allow mapping of Date to Calendar if (Date.class.isAssignableFrom(src) && dest == Calendar.class) return true; // Allow mapping of Calendar to java.sql.Date if (Calendar.class.isAssignableFrom(src) && dest == java.sql.Date.class) return true; } Class destHeld = JavaUtils.getHolderValueType(dest); // Can always convert a null to an empty holder if (src == null) return (destHeld != null); if (destHeld != null) { if (destHeld.isAssignableFrom(src) || isConvertable(src, destHeld)) return true; } // If it's holder -> held or held -> holder, we're good Class srcHeld = JavaUtils.getHolderValueType(src); if (srcHeld != null) { if (dest.isAssignableFrom(srcHeld) || isConvertable(srcHeld, dest)) return true; } // If it's a MIME type mapping and we want a DataHandler, // then we're good. if (dest.getName().equals("javax.activation.DataHandler")) { String name = src.getName(); if (src == String.class || src == java.awt.Image.class || src == OctetStream.class || name.equals("javax.mail.internet.MimeMultipart") || name.equals("javax.xml.transform.Source")) return true; } if (src.getName().equals("javax.activation.DataHandler")) { if (dest == byte[].class) return true; if (dest.isArray() && dest.getComponentType() == byte[].class) return true; } if (dest.getName().equals("javax.activation.DataHandler")) { if (src == Object[].class) return true; if (src.isArray() && src.getComponentType() == Object[].class) return true; } if (obj instanceof java.io.InputStream) { if (dest == OctetStream.class) return true; } if (src.isPrimitive()) { return isConvertable(getWrapperClass(src),dest); } // ArrayOfT -> T[] ? if (dest.isArray()) { if (ArrayUtil.isConvertable(src, dest) == true) return true; } // T[] -> ArrayOfT ? if (src.isArray()) { if (ArrayUtil.isConvertable(src, dest) == true) return true; } return false; } /** * @deprecated Use {@link ImageIO#read(InputStream)} instead. */ public static Image getImageFromStream(InputStream is) { try { return ImageIO.read(is); } catch (Throwable t) { return null; } } // getImageFromStream /** * These are java keywords as specified at the following URL (sorted alphabetically). * http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#229308 * Note that false, true, and null are not strictly keywords; they are literal values, * but for the purposes of this array, they can be treated as literals. * ****** PLEASE KEEP THIS LIST SORTED IN ASCENDING ORDER ****** */ static final String keywords[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; /** Collator for comparing the strings */ static final Collator englishCollator = Collator.getInstance(Locale.ENGLISH); /** Use this character as suffix */ static final char keywordPrefix = '_'; /** * isJavaId * Returns true if the name is a valid java identifier. * @param id to check * @return boolean true/false **/ public static boolean isJavaId(String id) { if (id == null || id.equals("") || isJavaKeyword(id)) return false; if (!Character.isJavaIdentifierStart(id.charAt(0))) return false; for (int i=1; i<id.length(); i++) if (!Character.isJavaIdentifierPart(id.charAt(i))) return false; return true; } /** * checks if the input string is a valid java keyword. * @return boolean true/false */ public static boolean isJavaKeyword(String keyword) { return (Arrays.binarySearch(keywords, keyword, englishCollator) >= 0); } /** * Turn a java keyword string into a non-Java keyword string. (Right now * this simply means appending an underscore.) */ public static String makeNonJavaKeyword(String keyword){ return keywordPrefix + keyword; } /** * Converts text of the form * Foo[] to the proper class name for loading [LFoo */ public static String getLoadableClassName(String text) { if (text == null || text.indexOf("[") < 0 || text.charAt(0) == '[') return text; String className = text.substring(0,text.indexOf("[")); if (className.equals("byte")) className = "B"; else if (className.equals("char")) className = "C"; else if (className.equals("double")) className = "D"; else if (className.equals("float")) className = "F"; else if (className.equals("int")) className = "I"; else if (className.equals("long")) className = "J"; else if (className.equals("short")) className = "S"; else if (className.equals("boolean")) className = "Z"; else className = "L" + className + ";"; int i = text.indexOf("]"); while (i > 0) { className = "[" + className; i = text.indexOf("]", i+1); } return className; } /** * Converts text of the form * [LFoo to the Foo[] */ public static String getTextClassName(String text) { if (text == null || text.indexOf("[") != 0) return text; String className = ""; int index = 0; while(index < text.length() && text.charAt(index) == '[') { index ++; className += "[]"; } if (index < text.length()) { if (text.charAt(index)== 'B') className = "byte" + className; else if (text.charAt(index) == 'C') className = "char" + className; else if (text.charAt(index) == 'D') className = "double" + className; else if (text.charAt(index) == 'F') className = "float" + className; else if (text.charAt(index) == 'I') className = "int" + className; else if (text.charAt(index) == 'J') className = "long" + className; else if (text.charAt(index) == 'S') className = "short" + className; else if (text.charAt(index) == 'Z') className = "boolean" + className; else { className = text.substring(index+1, text.indexOf(";")) + className; } } return className; } /** * Map an XML name to a Java identifier per * the mapping rules of JSR 101 (in version 1.0 this is * "Chapter 20: Appendix: Mapping of XML Names" * * @param name is the xml name * @return the java name per JSR 101 specification */ public static String xmlNameToJava(String name) { // protect ourselves from garbage if (name == null || name.equals("")) return name; char[] nameArray = name.toCharArray(); int nameLen = name.length(); StringBuffer result = new StringBuffer(nameLen); boolean wordStart = false; // The mapping indicates to convert first character. int i = 0; while (i < nameLen && (isPunctuation(nameArray[i]) || !Character.isJavaIdentifierStart(nameArray[i]))) { i++; } if (i < nameLen) { // Decapitalization code used to be here, but we use the // Introspector function now after we filter out all bad chars. result.append(nameArray[i]); //wordStart = !Character.isLetter(nameArray[i]); wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0); } else { // The identifier cannot be mapped strictly according to // JSR 101 if (Character.isJavaIdentifierPart(nameArray[0])) { result.append("_" + nameArray[0]); } else { // The XML identifier does not contain any characters // we can map to Java. Using the length of the string // will make it somewhat unique. result.append("_" + nameArray.length); } } // The mapping indicates to skip over // all characters that are not letters or // digits. The first letter/digit // following a skipped character is // upper-cased. for (++i; i < nameLen; ++i) { char c = nameArray[i]; // if this is a bad char, skip it and remember to capitalize next // good character we encounter if (isPunctuation(c) || !Character.isJavaIdentifierPart(c)) { wordStart = true; continue; } if (wordStart && Character.isLowerCase(c)) { result.append(Character.toUpperCase(c)); } else { result.append(c); } // If c is not a character, but is a legal Java // identifier character, capitalize the next character. // For example: "22hi" becomes "22Hi" //wordStart = !Character.isLetter(c); wordStart = !Character.isLetter(c) && c != "_".charAt(0); } // covert back to a String String newName = result.toString(); // Follow JavaBean rules, but we need to check if the first // letter is uppercase first if (Character.isUpperCase(newName.charAt(0))) newName = Introspector.decapitalize(newName); // check for Java keywords if (isJavaKeyword(newName)) newName = makeNonJavaKeyword(newName); return newName; } // xmlNameToJava /** * Is this an XML punctuation character? */ private static boolean isPunctuation(char c) { return '-' == c || '.' == c || ':' == c || '\u00B7' == c || '\u0387' == c || '\u06DD' == c || '\u06DE' == c; } // isPunctuation /** * replace: * Like String.replace except that the old new items are strings. * * @param name string * @param oldT old text to replace * @param newT new text to use * @return replacement string **/ public static final String replace (String name, String oldT, String newT) { if (name == null) return ""; // Create a string buffer that is twice initial length. // This is a good starting point. StringBuffer sb = new StringBuffer(name.length()* 2); int len = oldT.length (); try { int start = 0; int i = name.indexOf (oldT, start); while (i >= 0) { sb.append(name.substring(start, i)); sb.append(newT); start = i+len; i = name.indexOf(oldT, start); } if (start < name.length()) sb.append(name.substring(start)); } catch (NullPointerException e) { } return new String(sb); } /** * Determines if the Class is a Holder class. If so returns Class of held type * else returns null * @param type the suspected Holder Class * @return class of held type or null */ public static Class getHolderValueType(Class type) { if (type != null) { Class[] intf = type.getInterfaces(); boolean isHolder = false; for (int i=0; i<intf.length && !isHolder; i++) { if (intf[i] == javax.xml.rpc.holders.Holder.class) { isHolder = true; } } if (isHolder == false) { return null; } // Holder is supposed to have a public value field. java.lang.reflect.Field field; try { field = type.getField("value"); } catch (Exception e) { field = null; } if (field != null) { return field.getType(); } } return null; } /** * Gets the Holder value. * @param holder Holder object * @return value object */ public static Object getHolderValue(Object holder) throws HolderException { if (!(holder instanceof javax.xml.rpc.holders.Holder)) { throw new HolderException(Messages.getMessage("badHolder00")); } try { Field valueField = holder.getClass().getField("value"); return valueField.get(holder); } catch (Exception e) { throw new HolderException(Messages.getMessage("exception01", e.getMessage())); } } /** * Sets the Holder value. * @param holder Holder object * @param value is the object value */ public static void setHolderValue(Object holder, Object value) throws HolderException { if (!(holder instanceof javax.xml.rpc.holders.Holder)) { throw new HolderException(Messages.getMessage("badHolder00")); } try { Field valueField = holder.getClass().getField("value"); if (valueField.getType().isPrimitive()) { if (value == null) ; // Don't need to set anything else valueField.set(holder, value); // Automatically unwraps value to primitive } else { valueField.set(holder, value); } } catch (Exception e) { throw new HolderException(Messages.getMessage("exception01", e.getMessage())); } } public static class HolderException extends Exception { public HolderException(String msg) { super(msg); } } /** * Used to cache a result from IsEnumClassSub(). * Class->Boolean mapping. */ private static WeakHashMap enumMap = new WeakHashMap(); /** * Determine if the class is a JAX-RPC enum class. * An enumeration class is recognized by * a getValue() method, a toString() method, a fromString(String) method * a fromValue(type) method and the lack * of a setValue(type) method */ public static boolean isEnumClass(Class cls) { Boolean b = (Boolean)enumMap.get(cls); if (b == null) { b = (isEnumClassSub(cls)) ? Boolean.TRUE : Boolean.FALSE; synchronized (enumMap) { enumMap.put(cls, b); } } return b.booleanValue(); } private static boolean isEnumClassSub(Class cls) { try { java.lang.reflect.Method[] methods = cls.getMethods(); java.lang.reflect.Method getValueMethod = null, fromValueMethod = null, setValueMethod = null, fromStringMethod = null; // linear search: in practice, this is faster than // sorting/searching a short array of methods. for (int i = 0; i < methods.length; i++) { String name = methods[i].getName(); if (name.equals("getValue") && methods[i].getParameterTypes().length == 0) { // getValue() getValueMethod = methods[i]; } else if (name.equals("fromString")) { // fromString(String s) Object[] params = methods[i].getParameterTypes(); if (params.length == 1 && params[0] == String.class) { fromStringMethod = methods[i]; } } else if (name.equals("fromValue") && methods[i].getParameterTypes().length == 1) { // fromValue(Something s) fromValueMethod = methods[i]; } else if (name.equals("setValue") && methods[i].getParameterTypes().length == 1) { // setValue(Something s) setValueMethod = methods[i]; } } // must have getValue and fromString, but not setValue // must also have toString(), but every Object subclass has that, so // no need to check for it. if (null != getValueMethod && null != fromStringMethod) { if (null != setValueMethod && setValueMethod.getParameterTypes().length == 1 && getValueMethod.getReturnType() == setValueMethod.getParameterTypes()[0]) { // setValue exists: return false return false; } else { return true; } } else { return false; } } catch (java.lang.SecurityException e) { return false; } // end of catch } public static String stackToString(Throwable e){ java.io.StringWriter sw= new java.io.StringWriter(1024); java.io.PrintWriter pw= new java.io.PrintWriter(sw); e.printStackTrace(pw); pw.close(); return sw.toString(); } /** * Tests the String 'value': * return 'false' if its 'false', '0', or 'no' - else 'true' * * Follow in 'C' tradition of boolean values: * false is specific (0), everything else is true; */ public static final boolean isTrue(String value) { return !isFalseExplicitly(value); } /** * Tests the String 'value': * return 'true' if its 'true', '1', or 'yes' - else 'false' */ public static final boolean isTrueExplicitly(String value) { return value != null && (value.equalsIgnoreCase("true") || value.equals("1") || value.equalsIgnoreCase("yes")); } /** * Tests the Object 'value': * if its null, return default. * if its a Boolean, return booleanValue() * if its an Integer, return 'false' if its '0' else 'true' * if its a String, return isTrueExplicitly((String)value). * All other types return 'true' */ public static final boolean isTrueExplicitly(Object value, boolean defaultVal) { if ( value == null ) return defaultVal; if ( value instanceof Boolean ) { return ((Boolean)value).booleanValue(); } if ( value instanceof Integer ) { return ((Integer)value).intValue() != 0; } if ( value instanceof String ) { return isTrueExplicitly( (String)value ); } return true; } public static final boolean isTrueExplicitly(Object value) { return isTrueExplicitly(value, false); } /** * Tests the Object 'value': * if its null, return default. * if its a Boolean, return booleanValue() * if its an Integer, return 'false' if its '0' else 'true' * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true' * All other types return 'true' */ public static final boolean isTrue(Object value, boolean defaultVal) { return !isFalseExplicitly(value, !defaultVal); } public static final boolean isTrue(Object value) { return isTrue(value, false); } /** * Tests the String 'value': * return 'true' if its 'false', '0', or 'no' - else 'false' * * Follow in 'C' tradition of boolean values: * false is specific (0), everything else is true; */ public static final boolean isFalse(String value) { return isFalseExplicitly(value); } /** * Tests the String 'value': * return 'true' if its null, 'false', '0', or 'no' - else 'false' */ public static final boolean isFalseExplicitly(String value) { return value == null || value.equalsIgnoreCase("false") || value.equals("0") || value.equalsIgnoreCase("no"); } /** * Tests the Object 'value': * if its null, return default. * if its a Boolean, return !booleanValue() * if its an Integer, return 'true' if its '0' else 'false' * if its a String, return isFalseExplicitly((String)value). * All other types return 'false' */ public static final boolean isFalseExplicitly(Object value, boolean defaultVal) { if ( value == null ) return defaultVal; if ( value instanceof Boolean ) { return !((Boolean)value).booleanValue(); } if ( value instanceof Integer ) { return ((Integer)value).intValue() == 0; } if ( value instanceof String ) { return isFalseExplicitly( (String)value ); } return false; } public static final boolean isFalseExplicitly(Object value) { return isFalseExplicitly(value, true); } /** * Tests the Object 'value': * if its null, return default. * if its a Boolean, return booleanValue() * if its an Integer, return 'false' if its '0' else 'true' * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true' * All other types return 'true' */ public static final boolean isFalse(Object value, boolean defaultVal) { return isFalseExplicitly(value, defaultVal); } public static final boolean isFalse(Object value) { return isFalse(value, true); } /** * Given the MIME type string, return the Java mapping. */ public static String mimeToJava(String mime) { if ("image/gif".equals(mime) || "image/jpeg".equals(mime)) { return "java.awt.Image"; } else if ("text/plain".equals(mime)) { return "java.lang.String"; } else if ("text/xml".equals(mime) || "application/xml".equals(mime)) { return "javax.xml.transform.Source"; } else if ("application/octet-stream".equals(mime)|| "application/octetstream".equals(mime)) { return "org.apache.axis.attachments.OctetStream"; } else if (mime != null && mime.startsWith("multipart/")) { return "javax.mail.internet.MimeMultipart"; } else { return "javax.activation.DataHandler"; } } // mimeToJava //avoid testing and possibly failing everytime. private static boolean checkForAttachmentSupport = true; private static boolean attachmentSupportEnabled = false; /** * Determine whether attachments are supported by checking if the following * classes are available: javax.activation.DataHandler, * javax.mail.internet.MimeMultipart. */ public static synchronized boolean isAttachmentSupported() { if (checkForAttachmentSupport) { //aviod testing and possibly failing everytime. checkForAttachmentSupport = false; try { // Attempt to resolve DataHandler and MimeMultipart and // javax.xml.transform.Source, all necessary for full // attachment support ClassUtils.forName("javax.activation.DataHandler"); ClassUtils.forName("javax.mail.internet.MimeMultipart"); attachmentSupportEnabled = true; } catch (Throwable t) { } log.debug(Messages.getMessage("attachEnabled") + " " + attachmentSupportEnabled); if(!attachmentSupportEnabled) { log.warn(Messages.getMessage("attachDisabled")); } } return attachmentSupportEnabled; } // isAttachmentSupported /** * Makes the value passed in <code>initValue</code> unique among the * {@link String} values contained in <code>values</code> by suffixing * it with a decimal digit suffix. */ public static String getUniqueValue(Collection values, String initValue) { if (!values.contains(initValue)) { return initValue; } else { StringBuffer unqVal = new StringBuffer(initValue); int beg = unqVal.length(), cur, end; while (Character.isDigit(unqVal.charAt(beg - 1))) { beg--; } if (beg == unqVal.length()) { unqVal.append('1'); } cur = end = unqVal.length() - 1; while (values.contains(unqVal.toString())) { if (unqVal.charAt(cur) < '9') { unqVal.setCharAt(cur, (char) (unqVal.charAt(cur) + 1)); } else { while (cur-- > beg) { if (unqVal.charAt(cur) < '9') { unqVal.setCharAt(cur, (char) (unqVal.charAt(cur) + 1)); break; } } // See if there's a need to insert a new digit. if (cur < beg) { unqVal.insert(++cur, '1'); end++; } while (cur < end) { unqVal.setCharAt(++cur, '0'); } } } return unqVal.toString(); } /* For else clause of selection-statement If(!values ... */ } /* For class method JavaUtils.getUniqueValue */ }
7,620
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/BeanUtils.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.AxisFault; import org.apache.axis.Constants; import org.apache.axis.InternalException; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.FieldDesc; import org.apache.axis.description.TypeDesc; import org.apache.commons.logging.Log; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Vector; public class BeanUtils { public static final Object[] noArgs = new Object[] {}; protected static Log log = LogFactory.getLog(BeanUtils.class.getName()); /** * Create a BeanPropertyDescriptor array for the indicated class. * @param javaType * @return an ordered array of properties */ public static BeanPropertyDescriptor[] getPd(Class javaType) { return getPd(javaType, null); } /** * Create a BeanPropertyDescriptor array for the indicated class. * @param javaType * @param typeDesc * @return an ordered array of properties */ public static BeanPropertyDescriptor[] getPd(Class javaType, TypeDesc typeDesc) { BeanPropertyDescriptor[] pd; try { final Class secJavaType = javaType; // Need doPrivileged access to do introspection. PropertyDescriptor[] rawPd = getPropertyDescriptors(secJavaType); pd = processPropertyDescriptors(rawPd,javaType,typeDesc); } catch (Exception e) { // this should never happen throw new InternalException(e); } return pd; } private static PropertyDescriptor[] getPropertyDescriptors(final Class secJavaType) { return (PropertyDescriptor[])AccessController.doPrivileged( new PrivilegedAction() { public Object run() { PropertyDescriptor[] result = null; // START FIX http://nagoya.apache.org/bugzilla/showattachment.cgi?attach_id=4937 try { // privileged code goes here if (AxisFault.class.isAssignableFrom(secJavaType)) { // Don't include AxisFault data result = Introspector. getBeanInfo(secJavaType,AxisFault.class). getPropertyDescriptors(); } else if (Throwable.class != secJavaType && Throwable.class.isAssignableFrom(secJavaType)) { // Don't include Throwable data result = Introspector. getBeanInfo(secJavaType,Throwable.class). getPropertyDescriptors(); } else { // privileged code goes here result = Introspector. getBeanInfo(secJavaType). getPropertyDescriptors(); } // END FIX http://nagoya.apache.org/bugzilla/showattachment.cgi?attach_id=4937 } catch (java.beans.IntrospectionException Iie) { } return result; } }); } /** * Return a list of properties in the bean which should be attributes */ public static Vector getBeanAttributes(Class javaType, TypeDesc typeDesc) { Vector ret = new Vector(); if (typeDesc == null) { // !!! Support old-style beanAttributeNames for now // See if this object defined the 'getAttributeElements' function // which returns a Vector of property names that are attributes try { Method getAttributeElements = javaType.getMethod("getAttributeElements", new Class [] {}); // get string array String[] array = (String[])getAttributeElements.invoke(null, noArgs); // convert it to a Vector ret = new Vector(array.length); for (int i = 0; i < array.length; i++) { ret.add(array[i]); } } catch (Exception e) { ret.clear(); } } else { FieldDesc [] fields = typeDesc.getFields(); if (fields != null) { for (int i = 0; i < fields.length; i++) { FieldDesc field = fields[i]; if (!field.isElement()) { ret.add(field.getFieldName()); } } } } return ret; } /** * This method attempts to sort the property descriptors using * the typeDesc and order defined in the class. * * This routine also looks for set(i, type) and get(i) methods and adjusts the * property to use these methods instead. These methods are generated by the * emitter for "collection" of properties (i.e. maxOccurs="unbounded" on an element). * JAX-RPC is silent on this issue, but web services depend on this kind of behaviour. * The method signatures were chosen to match bean indexed properties. */ public static BeanPropertyDescriptor[] processPropertyDescriptors( PropertyDescriptor[] rawPd, Class cls) { return processPropertyDescriptors(rawPd, cls, null); } public static BeanPropertyDescriptor[] processPropertyDescriptors( PropertyDescriptor[] rawPd, Class cls, TypeDesc typeDesc) { // Create a copy of the rawPd called myPd BeanPropertyDescriptor[] myPd = new BeanPropertyDescriptor[rawPd.length]; ArrayList pd = new ArrayList(); try { for (int i=0; i < rawPd.length; i++) { // Skip the special "any" field if (rawPd[i].getName().equals(Constants.ANYCONTENT)) continue; pd.add(new BeanPropertyDescriptor(rawPd[i])); } // Now look for public fields Field fields[] = cls.getFields(); if (fields != null && fields.length > 0) { // See if the field is in the list of properties // add it if not. for (int i=0; i < fields.length; i++) { Field f = fields[i]; // skip if field come from a java.* or javax.* package // WARNING: Is this going to make bad things happen for // users JavaBeans? Do they WANT these fields serialzed? String clsName = f.getDeclaringClass().getName(); if (clsName.startsWith("java.") || clsName.startsWith("javax.")) { continue; } // skip field if it is final, transient, or static if (!(Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers()) || Modifier.isTransient(f.getModifiers()))) { String fName = f.getName(); boolean found = false; for (int j=0; j< rawPd.length && !found; j++) { String pName = ((BeanPropertyDescriptor)pd.get(j)).getName(); if (pName.length() == fName.length() && pName.substring(0,1).equalsIgnoreCase( fName.substring(0,1))) { found = pName.length() == 1 || pName.substring(1).equals(fName.substring(1)); } } if (!found) { pd.add(new FieldPropertyDescriptor(f.getName(), f)); } } } } // If typeDesc meta data exists, re-order according to the fields if (typeDesc != null && typeDesc.getFields(true) != null) { ArrayList ordered = new ArrayList(); // Add the TypeDesc elements first FieldDesc[] fds = typeDesc.getFields(true); for (int i=0; i<fds.length; i++) { FieldDesc field = fds[i]; if (field.isElement()) { boolean found = false; for (int j=0; j<pd.size() && !found; j++) { if (field.getFieldName().equals( ((BeanPropertyDescriptor)pd.get(j)).getName())) { ordered.add(pd.remove(j)); found = true; } } } } // Add the remaining elements while (pd.size() > 0) { ordered.add(pd.remove(0)); } // Use the ordered list pd = ordered; } myPd = new BeanPropertyDescriptor[pd.size()]; for (int i=0; i <pd.size(); i++) { myPd[i] = (BeanPropertyDescriptor) pd.get(i); } } catch (Exception e) { log.error(Messages.getMessage("badPropertyDesc00", cls.getName()), e); throw new InternalException(e); } return myPd; } public static BeanPropertyDescriptor getAnyContentPD(Class javaType) { PropertyDescriptor [] pds = getPropertyDescriptors(javaType); return getSpecificPD(pds, Constants.ANYCONTENT); } public static BeanPropertyDescriptor getSpecificPD(PropertyDescriptor[] pds, String name) { for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; if (pd.getName().equals(name)) return new BeanPropertyDescriptor(pd); } return null; } public static BeanPropertyDescriptor getSpecificPD(BeanPropertyDescriptor[] pds, String name) { for (int i = 0; i < pds.length; i++) { BeanPropertyDescriptor pd = pds[i]; if (pd.getName().equals(name)) return pd; } return null; } }
7,621
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/DOM2Writer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.axis.Constants; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; /** * This class is a utility to serialize a DOM node as XML. This class * uses the <code>DOM Level 2</code> APIs. * The main difference between this class and DOMWriter is that this class * generates and prints out namespace declarations. * * @author Matthew J. Duftler (duftler@us.ibm.com) * @author Joseph Kesselman */ public class DOM2Writer { /** * Return a string containing this node serialized as XML. */ public static String nodeToString(Node node, boolean omitXMLDecl) { StringWriter sw = new StringWriter(); serializeAsXML(node, sw, omitXMLDecl); return sw.toString(); } /** * Serialize this node into the writer as XML. */ public static void serializeAsXML(Node node, Writer writer, boolean omitXMLDecl) { serializeAsXML(node, writer, omitXMLDecl, false); } /** * Serialize this node into the writer as XML. */ public static void serializeAsXML(Node node, Writer writer, boolean omitXMLDecl, boolean pretty) { PrintWriter out = new PrintWriter(writer); if (!omitXMLDecl) { out.print("<?xml version=\"1.0\" encoding=\""); out.print(XMLUtils.getEncoding()); out.println("\"?>"); } NSStack namespaceStack = new NSStack(); print(node, namespaceStack, node, out, pretty, 0); out.flush(); } private static void print(Node node, NSStack namespaceStack, Node startnode, PrintWriter out, boolean pretty, int indent) { if (node == null) { return; } boolean hasChildren = false; int type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE : { NodeList children = node.getChildNodes(); if (children != null) { int numChildren = children.getLength(); for (int i = 0; i < numChildren; i++) { print(children.item(i), namespaceStack, startnode, out, pretty, indent); } } break; } case Node.ELEMENT_NODE : { namespaceStack.push(); if (pretty) { for (int i = 0; i < indent; i++) out.print(' '); } out.print('<' + node.getNodeName()); String elPrefix = node.getPrefix(); String elNamespaceURI = node.getNamespaceURI(); if (elPrefix != null && elNamespaceURI != null && elPrefix.length() > 0) { boolean prefixIsDeclared = false; try { String namespaceURI = namespaceStack.getNamespaceURI(elPrefix); if (elNamespaceURI.equals(namespaceURI)) { prefixIsDeclared = true; } } catch (IllegalArgumentException e) { } if (!prefixIsDeclared) { printNamespaceDecl(node, namespaceStack, startnode, out); } } NamedNodeMap attrs = node.getAttributes(); int len = (attrs != null) ? attrs.getLength() : 0; for (int i = 0; i < len; i++) { Attr attr = (Attr)attrs.item(i); out.print(' ' + attr.getNodeName() +"=\"" + normalize(attr.getValue()) + '\"'); String attrPrefix = attr.getPrefix(); String attrNamespaceURI = attr.getNamespaceURI(); if (attrPrefix != null && attrNamespaceURI != null && attrPrefix.length() > 0) { boolean prefixIsDeclared = false; try { String namespaceURI = namespaceStack.getNamespaceURI(attrPrefix); if (attrNamespaceURI.equals(namespaceURI)) { prefixIsDeclared = true; } } catch (IllegalArgumentException e) { } if (!prefixIsDeclared) { printNamespaceDecl(attr, namespaceStack, startnode, out); } } } NodeList children = node.getChildNodes(); if (children != null) { int numChildren = children.getLength(); hasChildren = (numChildren > 0); if (hasChildren) { out.print('>'); if (pretty) out.print(JavaUtils.LS); } for (int i = 0; i < numChildren; i++) { print(children.item(i), namespaceStack, startnode, out, pretty, indent + 1); } } else { hasChildren = false; } if (!hasChildren) { out.print("/>"); if (pretty) out.print(JavaUtils.LS); } namespaceStack.pop(); break; } case Node.ENTITY_REFERENCE_NODE : { out.print('&'); out.print(node.getNodeName()); out.print(';'); break; } case Node.CDATA_SECTION_NODE : { out.print("<![CDATA["); out.print(node.getNodeValue()); out.print("]]>"); break; } case Node.TEXT_NODE : { out.print(normalize(node.getNodeValue())); break; } case Node.COMMENT_NODE : { out.print("<!--"); out.print(node.getNodeValue()); out.print("-->"); if (pretty) out.print(JavaUtils.LS); break; } case Node.PROCESSING_INSTRUCTION_NODE : { out.print("<?"); out.print(node.getNodeName()); String data = node.getNodeValue(); if (data != null && data.length() > 0) { out.print(' '); out.print(data); } out.println("?>"); if (pretty) out.print(JavaUtils.LS); break; } } if (type == Node.ELEMENT_NODE && hasChildren == true) { if (pretty) { for (int i = 0; i < indent; i++) out.print(' '); } out.print("</"); out.print(node.getNodeName()); out.print('>'); if (pretty) out.print(JavaUtils.LS); hasChildren = false; } } private static void printNamespaceDecl(Node node, NSStack namespaceStack, Node startnode, PrintWriter out) { switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE : { printNamespaceDecl(((Attr)node).getOwnerElement(), node, namespaceStack, startnode, out); break; } case Node.ELEMENT_NODE : { printNamespaceDecl((Element)node, node, namespaceStack, startnode, out); break; } } } private static void printNamespaceDecl(Element owner, Node node, NSStack namespaceStack, Node startnode, PrintWriter out) { String namespaceURI = node.getNamespaceURI(); String prefix = node.getPrefix(); if (!(namespaceURI.equals(Constants.NS_URI_XMLNS) && prefix.equals("xmlns")) && !(namespaceURI.equals(Constants.NS_URI_XML) && prefix.equals("xml"))) { if (XMLUtils.getNamespace(prefix, owner, startnode) == null) { out.print(" xmlns:" + prefix + "=\"" + namespaceURI + '\"'); } } else { prefix = node.getLocalName(); namespaceURI = node.getNodeValue(); } namespaceStack.add(namespaceURI, prefix); } public static String normalize(String s) { return XMLUtils.xmlEncodeString(s); } }
7,622
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/SessionUtils.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.Random; /** * Code borrowed from AuthenticatorBase.java for generating a secure id's. */ public class SessionUtils { /** Field log */ protected static Log log = LogFactory.getLog(SessionUtils.class.getName()); /** * The number of random bytes to include when generating a * session identifier. */ protected static final int SESSION_ID_BYTES = 16; /** * A random number generator to use when generating session identifiers. */ protected static Random random = null; /** * The Java class name of the random number generator class to be used * when generating session identifiers. */ protected static String randomClass = "java.security.SecureRandom"; /** * Host name/ip. */ private static String thisHost = null; /** * Generate and return a new session identifier. * * @return a new session id */ public static synchronized String generateSessionId() { // Generate a byte array containing a session identifier byte bytes[] = new byte[SESSION_ID_BYTES]; getRandom().nextBytes(bytes); // Render the result as a String of hexadecimal digits StringBuffer result = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { byte b1 = (byte) ((bytes[i] & 0xf0) >> 4); byte b2 = (byte) (bytes[i] & 0x0f); if (b1 < 10) { result.append((char) ('0' + b1)); } else { result.append((char) ('A' + (b1 - 10))); } if (b2 < 10) { result.append((char) ('0' + b2)); } else { result.append((char) ('A' + (b2 - 10))); } } return (result.toString()); } /** * Generate and return a new session identifier. * * @return a new session. */ public static synchronized Long generateSession() { return new Long(getRandom().nextLong()); } /** * Return the random number generator instance we should use for * generating session identifiers. If there is no such generator * currently defined, construct and seed a new one. * * @return Random object */ private static synchronized Random getRandom() { if (random == null) { try { Class clazz = Class.forName(randomClass); random = (Random) clazz.newInstance(); } catch (Exception e) { random = new java.util.Random(); } } return (random); } }
7,623
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/Messages.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.i18n.MessageBundle; import org.apache.axis.i18n.MessagesConstants; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @see org.apache.axis.i18n.Messages * * @author Richard A. Sitze (rsitze@us.ibm.com) * @author Karl Moss (kmoss@macromedia.com) * @author Glen Daniels (gdaniels@apache.org) */ public class Messages { private static final Class thisClass = Messages.class; private static final String projectName = MessagesConstants.projectName; private static final String resourceName = MessagesConstants.resourceName; private static final Locale locale = MessagesConstants.locale; private static final String packageName = getPackage(thisClass.getName()); private static final ClassLoader classLoader = thisClass.getClassLoader(); private static final ResourceBundle parent = (MessagesConstants.rootPackageName == packageName) ? null : MessagesConstants.rootBundle; /***** NO NEED TO CHANGE ANYTHING BELOW *****/ private static final MessageBundle messageBundle = new MessageBundle(projectName, packageName, resourceName, locale, classLoader, parent); /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @return The formatted message */ public static String getMessage(String key) throws MissingResourceException { return messageBundle.getMessage(key); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @return The formatted message */ public static String getMessage(String key, String arg0) throws MissingResourceException { return messageBundle.getMessage(key, arg0); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2, arg3); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param arg0 The argument to place in variable {0} * @param arg1 The argument to place in variable {1} * @param arg2 The argument to place in variable {2} * @param arg3 The argument to place in variable {3} * @param arg4 The argument to place in variable {4} * @return The formatted message */ public static String getMessage(String key, String arg0, String arg1, String arg2, String arg3, String arg4) throws MissingResourceException { return messageBundle.getMessage(key, arg0, arg1, arg2, arg3, arg4); } /** * Get a message from resource.properties from the package of the given object. * @param key The resource key * @param args An array of objects to place in corresponding variables * @return The formatted message */ public static String getMessage(String key, String[] args) throws MissingResourceException { return messageBundle.getMessage(key, args); } public static ResourceBundle getResourceBundle() { return messageBundle.getResourceBundle(); } public static MessageBundle getMessageBundle() { return messageBundle; } private static final String getPackage(String name) { return name.substring(0, name.lastIndexOf('.')).intern(); } }
7,624
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/Options.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils ; /** * General purpose command line options parser. * If this is used outside of Axis just remove the Axis specific sections. * * @author Doug Davis (dug@us.ibm.com) */ import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Vector; public class Options { protected static Log log = LogFactory.getLog(Options.class.getName()); String args[] = null ; Vector usedArgs = null ; URL defaultURL = null ; ////////////////////////////////////////////////////////////////////////// // SOASS (Start of Axis Specific Stuff) // EOASS ////////////////////////////////////////////////////////////////////////// /** * Constructor - just pass in the <b>args</b> from the command line. */ public Options(String _args[]) throws MalformedURLException { if (_args == null) { _args = new String [] {}; } args = _args ; usedArgs = null ; defaultURL = new URL("http://localhost:8080/axis/servlet/AxisServlet"); /////////////////////////////////////////////////////////////////////// // SOASS /* Process these well known options first */ /******************************************/ try { getURL(); } catch( MalformedURLException e ) { log.error( Messages.getMessage("cantDoURL00") ); throw e ; } getUser(); getPassword(); // EOASS /////////////////////////////////////////////////////////////////////// } public void setDefaultURL(String url) throws MalformedURLException { defaultURL = new URL(url); } public void setDefaultURL(URL url) { defaultURL = url ; } /** * Returns an int specifying the number of times that the flag was * specified on the command line. Once this flag is looked for you * must save the result because if you call it again for the same * flag you'll get zero. */ public int isFlagSet(char optChar) { int value = 0 ; int loop ; int i ; for ( loop = 0 ; usedArgs != null && loop < usedArgs.size() ; loop++ ) { String arg = (String) usedArgs.elementAt(loop); if ( arg.charAt(0) != '-' ) continue ; for ( i = 0 ; i < arg.length() ; i++ ) if ( arg.charAt(i) == optChar ) value++ ; } for ( loop = 0 ; loop < args.length ; loop++ ) { if ( args[loop] == null || args[loop].length() == 0 ) continue ; if ( args[loop].charAt(0) != '-' ) continue ; while (args[loop] != null && (i = args[loop].indexOf(optChar)) != -1) { args[loop] = args[loop].substring(0, i) + args[loop].substring(i+1) ; if ( args[loop].length() == 1 ) args[loop] = null ; value++ ; if ( usedArgs == null ) usedArgs = new Vector(); usedArgs.add( "-" + optChar ); } } return( value ); } /** * Returns a string (or null) specifying the value for the passed * option. If the option isn't there then null is returned. The * option's value can be specified one of two ways: * -x value * -xvalue * Note that: -ax value * is not value (meaning flag 'a' followed by option 'x'. * Options with values must be the first char after the '-'. * If the option is specified more than once then the last one wins. */ public String isValueSet(char optChar) { String value = null ; int loop ; int i ; for ( loop = 0 ; usedArgs != null && loop < usedArgs.size() ; loop++ ) { String arg = (String) usedArgs.elementAt(loop); if ( arg.charAt(0) != '-' || arg.charAt(1) != optChar ) continue ; value = arg.substring(2); if ( loop+1 < usedArgs.size() ) value = (String) usedArgs.elementAt(++loop); } for ( loop = 0 ; loop < args.length ; loop++ ) { if ( args[loop] == null || args[loop].length() == 0 ) continue ; if ( args[loop].charAt(0) != '-' ) continue ; i = args[loop].indexOf( optChar ); if ( i != 1 ) continue ; if ( i != args[loop].length()-1 ) { // Not at end of arg, so use rest of arg as value value = args[loop].substring(i+1) ; args[loop] = args[loop].substring(0, i); } else { // Remove the char from the current arg args[loop] = args[loop].substring(0, i); // Nothing after char so use next arg if ( loop+1 < args.length && args[loop+1] != null ) { // Next arg is there and non-null if ( args[loop+1].charAt(0) != '-' ) { value = args[loop+1]; args[loop+1] = null ; } } else { // Next is null or not there - do nothing // value = null ; } } if ( args[loop].length() == 1 ) args[loop] = null ; // For now, keep looping to get that last on there // break ; } if ( value != null ) { if ( usedArgs == null ) usedArgs = new Vector(); usedArgs.add( "-" + optChar ); if ( value.length() > 0 ) usedArgs.add( value ); } return( value ); } /** * This just returns a string with the unprocessed flags - mainly * for error reporting - so you can report the unknown flags. */ public String getRemainingFlags() { StringBuffer sb = null ; int loop ; for ( loop = 0 ; loop < args.length ; loop++ ) { if ( args[loop] == null || args[loop].length() == 0 ) continue ; if ( args[loop].charAt(0) != '-' ) continue ; if ( sb == null ) sb = new StringBuffer(); sb.append( args[loop].substring(1) ); } return( sb == null ? null : sb.toString() ); } /** * This returns an array of unused args - these are the non-option * args from the command line. */ public String[] getRemainingArgs() { ArrayList al = null ; int loop ; for ( loop = 0 ; loop < args.length ; loop++ ) { if ( args[loop] == null || args[loop].length() == 0 ) continue ; if ( args[loop].charAt(0) == '-' ) continue ; if ( al == null ) al = new ArrayList(); al.add( (String) args[loop] ); } if ( al == null ) return( null ); String a[] = new String[ al.size() ]; for ( loop = 0 ; loop < al.size() ; loop++ ) a[loop] = (String) al.get(loop); return( a ); } ////////////////////////////////////////////////////////////////////////// // SOASS public String getURL() throws MalformedURLException { String tmp ; String host = null ; // -h also -l (url) String port = null ; // -p String servlet = null ; // -s also -f (file) String protocol = null ; URL url = null ; // Just in case... org.apache.axis.client.Call.initialize(); if ( (tmp = isValueSet( 'l' )) != null ) { url = new URL( tmp ); host = url.getHost(); port = "" + url.getPort(); servlet = url.getFile(); protocol = url.getProtocol(); } if ( (tmp = isValueSet( 'f' )) != null ) { host = ""; port = "-1"; servlet = tmp; protocol = "file"; } tmp = isValueSet( 'h' ); if ( host == null ) host = tmp ; tmp = isValueSet( 'p' ); if ( port == null ) port = tmp ; tmp = isValueSet( 's' ); if ( servlet == null ) servlet = tmp ; if ( host == null ) host = defaultURL.getHost(); if ( port == null ) port = "" + defaultURL.getPort(); if ( servlet == null ) servlet = defaultURL.getFile(); else if ( servlet.length()>0 && servlet.charAt(0)!='/' ) servlet = "/" + servlet ; if (url == null) { if (protocol == null) protocol = defaultURL.getProtocol(); tmp = protocol + "://" + host ; if ( port != null && !port.equals("-1")) tmp += ":" + port ; if ( servlet != null ) tmp += servlet ; } else tmp = url.toString(); log.debug( Messages.getMessage("return02", "getURL", tmp) ); return( tmp ); } public String getHost() { try { URL url = new URL(getURL()); return( url.getHost() ); } catch( Exception exp ) { return( "localhost" ); } } public int getPort() { try { URL url = new URL(getURL()); return( url.getPort() ); } catch( Exception exp ) { return( -1 ); } } public String getUser() { return( isValueSet('u') ); } public String getPassword() { return( isValueSet('w') ); } // EOASS ////////////////////////////////////////////////////////////////////////// }
7,625
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/ByteArray.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import org.apache.axis.AxisEngine; import org.apache.axis.AxisProperties; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Class ByteArray */ public class ByteArray extends OutputStream { protected static double DEFAULT_CACHE_INCREMENT = 2.5; protected static int DEFAULT_RESIDENT_SIZE = 512 * 1024 * 1024; // 512 MB protected static boolean DEFAULT_ENABLE_BACKING_STORE = true; protected static int WORKING_BUFFER_SIZE = 8192; protected org.apache.axis.utils.ByteArrayOutputStream cache = null; protected int max_size = 0; protected File bs_handle = null; protected OutputStream bs_stream = null; protected long count = 0; protected boolean enableBackingStore = DEFAULT_ENABLE_BACKING_STORE; public boolean isEnableBackingStore() { return enableBackingStore; } public void setEnableBackingStore(boolean enableBackingStore) { this.enableBackingStore = enableBackingStore; } public static boolean isDEFAULT_ENABLE_BACKING_STORE() { return DEFAULT_ENABLE_BACKING_STORE; } public static void setDEFAULT_ENABLE_BACKING_STORE( boolean DEFAULT_ENABLE_BACKING_STORE) { ByteArray.DEFAULT_ENABLE_BACKING_STORE = DEFAULT_ENABLE_BACKING_STORE; } public static int getDEFAULT_RESIDENT_SIZE() { return DEFAULT_RESIDENT_SIZE; } public static void setDEFAULT_RESIDENT_SIZE(int DEFAULT_RESIDENT_SIZE) { ByteArray.DEFAULT_RESIDENT_SIZE = DEFAULT_RESIDENT_SIZE; } public static double getDEFAULT_CACHE_INCREMENT() { return DEFAULT_CACHE_INCREMENT; } public static void setDEFAULT_CACHE_INCREMENT( double DEFAULT_CACHE_INCREMENT) { ByteArray.DEFAULT_CACHE_INCREMENT = DEFAULT_CACHE_INCREMENT; } static { String value; value = AxisProperties.getProperty( AxisEngine.PROP_BYTE_BUFFER_CACHE_INCREMENT, "" + DEFAULT_CACHE_INCREMENT); DEFAULT_CACHE_INCREMENT = Double.parseDouble(value); value = AxisProperties.getProperty( AxisEngine.PROP_BYTE_BUFFER_RESIDENT_MAX_SIZE, "" + DEFAULT_RESIDENT_SIZE); DEFAULT_RESIDENT_SIZE = Integer.parseInt(value); value = AxisProperties.getProperty( AxisEngine.PROP_BYTE_BUFFER_WORK_BUFFER_SIZE, "" + WORKING_BUFFER_SIZE); WORKING_BUFFER_SIZE = Integer.parseInt(value); value = AxisProperties.getProperty(AxisEngine.PROP_BYTE_BUFFER_BACKING, "" + DEFAULT_ENABLE_BACKING_STORE); if (value.equalsIgnoreCase("true") || value.equals("1") || value.equalsIgnoreCase("yes")) { DEFAULT_ENABLE_BACKING_STORE = true; } else { DEFAULT_ENABLE_BACKING_STORE = false; } } /** * Constructor ByteArray */ public ByteArray() { this(DEFAULT_RESIDENT_SIZE); } /** * Constructor ByteArray * * @param max_resident_size */ public ByteArray(int max_resident_size) { this(0, max_resident_size); } /** * Constructor ByteArray * * @param probable_size * @param max_resident_size */ public ByteArray(int probable_size, int max_resident_size) { if (probable_size > max_resident_size) { probable_size = 0; } if (probable_size < WORKING_BUFFER_SIZE) { probable_size = WORKING_BUFFER_SIZE; } cache = new org.apache.axis.utils.ByteArrayOutputStream(probable_size); max_size = max_resident_size; } /** * Method write * * @param bytes * @throws IOException */ public void write(byte bytes[]) throws IOException { write(bytes, 0, bytes.length); } /** * Method write * * @param bytes * @param start * @param length * @throws IOException */ public void write(byte bytes[], int start, int length) throws IOException { count += length; if (cache != null) { increaseCapacity(length); } if (cache != null) { cache.write(bytes, start, length); } else if (bs_stream != null) { bs_stream.write(bytes, start, length); } else { throw new IOException("ByteArray does not have a backing store!"); } } /** * Method write * * @param b * @throws IOException */ public void write(int b) throws IOException { count += 1; if (cache != null) { increaseCapacity(1); } if (cache != null) { cache.write(b); } else if (bs_stream != null) { bs_stream.write(b); } else { throw new IOException("ByteArray does not have a backing store!"); } } /** * Method close * * @throws IOException */ public void close() throws IOException { if (bs_stream != null) { bs_stream.close(); bs_stream = null; } } /** * Method size * * @return */ public long size() { return count; } /** * Method flush * * @throws IOException */ public void flush() throws IOException { if (bs_stream != null) { bs_stream.flush(); } } /** * Method increaseCapacity * * @param count * @throws IOException */ protected void increaseCapacity(int count) throws IOException { if (cache == null) { return; } if (count + cache.size() <= max_size) { return; } else if (enableBackingStore) { switchToBackingStore(); } else { throw new IOException("ByteArray can not increase capacity by " + count + " due to max size limit of " + max_size); } } /** * Method discardBuffer */ public synchronized void discardBuffer() { cache = null; if (bs_stream != null) { try { bs_stream.close(); } catch (IOException e) { // just ignore it... } bs_stream = null; } discardBackingStore(); } /** * Method makeInputStream * * @return * @throws IOException * @throws FileNotFoundException */ protected InputStream makeInputStream() throws IOException, FileNotFoundException { close(); if (cache != null) { return new ByteArrayInputStream(cache.toByteArray()); } else if (bs_handle != null) { return createBackingStoreInputStream(); } else { return null; } } /** * Method finalize */ protected void finalize() { discardBuffer(); } /** * Method switchToBackingStore * * @throws IOException */ protected void switchToBackingStore() throws IOException { bs_handle = File.createTempFile("Axis", ".msg"); bs_handle.createNewFile(); bs_handle.deleteOnExit(); bs_stream = new FileOutputStream(bs_handle); bs_stream.write(cache.toByteArray()); cache = null; } /** * Method getBackingStoreFileName * * @throws IOException */ public String getBackingStoreFileName() throws IOException { String fileName = null; if (bs_handle != null) { fileName = bs_handle.getCanonicalPath(); } return fileName; } /** * Method discardBackingStore */ protected void discardBackingStore() { if (bs_handle != null) { bs_handle.delete(); bs_handle = null; } } /** * Method createBackingStoreInputStream * * @return * @throws FileNotFoundException */ protected InputStream createBackingStoreInputStream() throws FileNotFoundException { try { return new BufferedInputStream( new FileInputStream(bs_handle.getCanonicalPath())); } catch (IOException e) { throw new FileNotFoundException(bs_handle.getAbsolutePath()); } } /** * Method toByteArray * * @return * @throws IOException */ public byte[] toByteArray() throws IOException { InputStream inp = this.makeInputStream(); byte[] buf = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); buf = new byte[WORKING_BUFFER_SIZE]; int len; while ((len = inp.read(buf, 0, WORKING_BUFFER_SIZE)) != -1) { baos.write(buf, 0, len); } inp.close(); discardBackingStore(); return baos.toByteArray(); } /** * Method writeTo * * @param os * @throws IOException */ public void writeTo(OutputStream os) throws IOException { InputStream inp = this.makeInputStream(); byte[] buf = null; buf = new byte[WORKING_BUFFER_SIZE]; int len; while ((len = inp.read(buf, 0, WORKING_BUFFER_SIZE)) != -1) { os.write(buf, 0, len); } inp.close(); discardBackingStore(); } }
7,626
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/ByteArrayOutputStream.java
/* * Copyright 2003,2004 The Apache Software Foundation. * * 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.axis.utils; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; /** * This class implements an output stream in which the data is * written into a byte array. The buffer automatically grows as data * is written to it. * <p> * The data can be retrieved using <code>toByteArray()</code> and * <code>toString()</code>. * <p> * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in * this class can be called after the stream has been closed without * generating an <tt>IOException</tt>. * <p> * This is an alternative implementation of the java.io.ByteArrayOutputStream * class. The original implementation only allocates 32 bytes at the beginning. * As this class is designed for heavy duty it starts at 1024 bytes. In contrast * to the original it doesn't reallocate the whole memory block but allocates * additional buffers. This way no buffers need to be garbage collected and * the contents don't have to be copied to the new buffer. This class is * designed to behave exactly like the original. The only exception is the * deprecated toString(int) method that has been ignored. * * @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a> */ public class ByteArrayOutputStream extends OutputStream { private List buffers = new java.util.ArrayList(); private int currentBufferIndex; private int filledBufferSum; private byte[] currentBuffer; private int count; /** * Creates a new byte array output stream. The buffer capacity is * initially 1024 bytes, though its size increases if necessary. */ public ByteArrayOutputStream() { this(1024); } /** * Creates a new byte array output stream, with a buffer capacity of * the specified size, in bytes. * * @param size the initial size. * @throws IllegalArgumentException if size is negative. */ public ByteArrayOutputStream(int size) { if (size < 0) { throw new IllegalArgumentException( Messages.getMessage("illegalArgumentException01", Integer.toString(size))); } needNewBuffer(size); } private byte[] getBuffer(int index) { return (byte[]) buffers.get(index); } private void needNewBuffer(int newcount) { if (currentBufferIndex < buffers.size() - 1) { //Recycling old buffer filledBufferSum += currentBuffer.length; currentBufferIndex++; currentBuffer = getBuffer(currentBufferIndex); } else { //Creating new buffer int newBufferSize; if (currentBuffer == null) { newBufferSize = newcount; filledBufferSum = 0; } else { newBufferSize = Math.max(currentBuffer.length << 1, newcount - filledBufferSum); filledBufferSum += currentBuffer.length; } currentBufferIndex++; currentBuffer = new byte[newBufferSize]; buffers.add(currentBuffer); } } /** * @see java.io.OutputStream#write(byte[], int, int) */ public synchronized void write(byte[] b, int off, int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException( Messages.getMessage("indexOutOfBoundsException00")); } else if (len == 0) { return; } int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; while (remaining > 0) { int part = Math.min(remaining, currentBuffer.length - inBufferPos); System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; if (remaining > 0) { needNewBuffer(newcount); inBufferPos = 0; } } count = newcount; } /** * Calls the write(byte[]) method. * * @see java.io.OutputStream#write(int) */ public synchronized void write(int b) { write(new byte[]{(byte) b}, 0, 1); } /** * @see java.io.ByteArrayOutputStream#size() */ public int size() { return count; } /** * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in * this class can be called after the stream has been closed without * generating an <tt>IOException</tt>. * * @throws IOException in case an I/O error occurs */ public void close() throws IOException { //nop } /** * @see java.io.ByteArrayOutputStream#reset() */ public synchronized void reset() { count = 0; filledBufferSum = 0; currentBufferIndex = 0; currentBuffer = getBuffer(currentBufferIndex); } /** * @see java.io.ByteArrayOutputStream#writeTo(OutputStream) */ public synchronized void writeTo(OutputStream out) throws IOException { int remaining = count; for (int i = 0; i < buffers.size(); i++) { byte[] buf = getBuffer(i); int c = Math.min(buf.length, remaining); out.write(buf, 0, c); remaining -= c; if (remaining == 0) { break; } } } /** * @see java.io.ByteArrayOutputStream#toByteArray() */ public synchronized byte[] toByteArray() { int remaining = count; int pos = 0; byte[] newbuf = new byte[count]; for (int i = 0; i < buffers.size(); i++) { byte[] buf = getBuffer(i); int c = Math.min(buf.length, remaining); System.arraycopy(buf, 0, newbuf, pos, c); pos += c; remaining -= c; if (remaining == 0) { break; } } return newbuf; } /** * @see java.io.ByteArrayOutputStream#toString() */ public String toString() { return new String(toByteArray()); } /** * @see java.io.ByteArrayOutputStream#toString(String) */ public String toString(String enc) throws UnsupportedEncodingException { return new String(toByteArray(), enc); } }
7,627
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/XMLChar.java
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * 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.axis.utils; /** * This class defines the basic XML character properties. The data * in this class can be used to verify that a character is a valid * XML character or if the character is a space, name start, or name * character. * <p> * A series of convenience methods are supplied to ease the burden * of the developer. Because inlining the checks can improve per * character performance, the tables of character properties are * public. Using the character as an index into the <code>CHARS</code> * array and applying the appropriate mask flag (e.g. * <code>MASK_VALID</code>), yields the same results as calling the * convenience methods. There is one exception: check the comments * for the <code>isValid</code> method for details. * * @author Glenn Marcy, IBM * @author Andy Clark, IBM * @author Eric Ye, IBM * @author Arnaud Le Hors, IBM * @author Rahul Srivastava, Sun Microsystems Inc. */ public class XMLChar { // // Constants // /** Character flags. */ private static final byte[] CHARS = new byte[1 << 16]; /** Valid character mask. */ public static final int MASK_VALID = 0x01; /** Space character mask. */ public static final int MASK_SPACE = 0x02; /** Name start character mask. */ public static final int MASK_NAME_START = 0x04; /** Name character mask. */ public static final int MASK_NAME = 0x08; /** Pubid character mask. */ public static final int MASK_PUBID = 0x10; /** * Content character mask. Special characters are those that can * be considered the start of markup, such as '&lt;' and '&amp;'. * The various newline characters are considered special as well. * All other valid XML characters can be considered content. * <p> * This is an optimization for the inner loop of character scanning. */ public static final int MASK_CONTENT = 0x20; /** NCName start character mask. */ public static final int MASK_NCNAME_START = 0x40; /** NCName character mask. */ public static final int MASK_NCNAME = 0x80; // // Static initialization // static { // // [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | // [#xE000-#xFFFD] | [#x10000-#x10FFFF] // int charRange[] = { 0x0009, 0x000A, 0x000D, 0x000D, 0x0020, 0xD7FF, 0xE000, 0xFFFD, }; // // [3] S ::= (#x20 | #x9 | #xD | #xA)+ // int spaceChar[] = { 0x0020, 0x0009, 0x000D, 0x000A, }; // // [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | // CombiningChar | Extender // int nameChar[] = { 0x002D, 0x002E, // '-' and '.' }; // // [5] Name ::= (Letter | '_' | ':') (NameChar)* // int nameStartChar[] = { 0x003A, 0x005F, // ':' and '_' }; // // [13] PubidChar ::= #x20 | 0xD | 0xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] // int pubidChar[] = { 0x000A, 0x000D, 0x0020, 0x0021, 0x0023, 0x0024, 0x0025, 0x003D, 0x005F }; int pubidRange[] = { 0x0027, 0x003B, 0x003F, 0x005A, 0x0061, 0x007A }; // // [84] Letter ::= BaseChar | Ideographic // int letterRange[] = { // BaseChar 0x0041, 0x005A, 0x0061, 0x007A, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0388, 0x038A, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E87, 0x0E88, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB2, 0x0EB3, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1102, 0x1103, 0x1105, 0x1107, 0x110B, 0x110C, 0x110E, 0x1112, 0x1154, 0x1155, 0x115F, 0x1161, 0x116D, 0x116E, 0x1172, 0x1173, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BC, 0x11C2, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x212A, 0x212B, 0x2180, 0x2182, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0xAC00, 0xD7A3, // Ideographic 0x3021, 0x3029, 0x4E00, 0x9FA5, }; int letterChar[] = { // BaseChar 0x0386, 0x038C, 0x03DA, 0x03DC, 0x03DE, 0x03E0, 0x0559, 0x06D5, 0x093D, 0x09B2, 0x0A5E, 0x0A8D, 0x0ABD, 0x0AE0, 0x0B3D, 0x0B9C, 0x0CDE, 0x0E30, 0x0E84, 0x0E8A, 0x0E8D, 0x0EA5, 0x0EA7, 0x0EB0, 0x0EBD, 0x1100, 0x1109, 0x113C, 0x113E, 0x1140, 0x114C, 0x114E, 0x1150, 0x1159, 0x1163, 0x1165, 0x1167, 0x1169, 0x1175, 0x119E, 0x11A8, 0x11AB, 0x11BA, 0x11EB, 0x11F0, 0x11F9, 0x1F59, 0x1F5B, 0x1F5D, 0x1FBE, 0x2126, 0x212E, // Ideographic 0x3007, }; // // [87] CombiningChar ::= ... // int combiningCharRange[] = { 0x0300, 0x0345, 0x0360, 0x0361, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05C1, 0x05C2, 0x064B, 0x0652, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x0901, 0x0903, 0x093E, 0x094C, 0x0951, 0x0954, 0x0962, 0x0963, 0x0981, 0x0983, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09E2, 0x09E3, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0B01, 0x0B03, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0E34, 0x0E3A, 0x0E47, 0x0E4E, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0ECD, 0x0F18, 0x0F19, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x20D0, 0x20DC, 0x302A, 0x302F, }; int combiningCharChar[] = { 0x05BF, 0x05C4, 0x0670, 0x093C, 0x094D, 0x09BC, 0x09BE, 0x09BF, 0x09D7, 0x0A02, 0x0A3C, 0x0A3E, 0x0A3F, 0x0ABC, 0x0B3C, 0x0BD7, 0x0D57, 0x0E31, 0x0EB1, 0x0F35, 0x0F37, 0x0F39, 0x0F3E, 0x0F3F, 0x0F97, 0x0FB9, 0x20E1, 0x3099, 0x309A, }; // // [88] Digit ::= ... // int digitRange[] = { 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, }; // // [89] Extender ::= ... // int extenderRange[] = { 0x3031, 0x3035, 0x309D, 0x309E, 0x30FC, 0x30FE, }; int extenderChar[] = { 0x00B7, 0x02D0, 0x02D1, 0x0387, 0x0640, 0x0E46, 0x0EC6, 0x3005, }; // // SpecialChar ::= '<', '&', '\n', '\r', ']' // int specialChar[] = { '<', '&', '\n', '\r', ']', }; // // Initialize // // set valid characters for (int i = 0; i < charRange.length; i += 2) { for (int j = charRange[i]; j <= charRange[i + 1]; j++) { CHARS[j] |= MASK_VALID | MASK_CONTENT; } } // remove special characters for (int i = 0; i < specialChar.length; i++) { CHARS[specialChar[i]] = (byte)(CHARS[specialChar[i]] & ~MASK_CONTENT); } // set space characters for (int i = 0; i < spaceChar.length; i++) { CHARS[spaceChar[i]] |= MASK_SPACE; } // set name start characters for (int i = 0; i < nameStartChar.length; i++) { CHARS[nameStartChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } for (int i = 0; i < letterRange.length; i += 2) { for (int j = letterRange[i]; j <= letterRange[i + 1]; j++) { CHARS[j] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } } for (int i = 0; i < letterChar.length; i++) { CHARS[letterChar[i]] |= MASK_NAME_START | MASK_NAME | MASK_NCNAME_START | MASK_NCNAME; } // set name characters for (int i = 0; i < nameChar.length; i++) { CHARS[nameChar[i]] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < digitRange.length; i += 2) { for (int j = digitRange[i]; j <= digitRange[i + 1]; j++) { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } for (int i = 0; i < combiningCharRange.length; i += 2) { for (int j = combiningCharRange[i]; j <= combiningCharRange[i + 1]; j++) { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } for (int i = 0; i < combiningCharChar.length; i++) { CHARS[combiningCharChar[i]] |= MASK_NAME | MASK_NCNAME; } for (int i = 0; i < extenderRange.length; i += 2) { for (int j = extenderRange[i]; j <= extenderRange[i + 1]; j++) { CHARS[j] |= MASK_NAME | MASK_NCNAME; } } for (int i = 0; i < extenderChar.length; i++) { CHARS[extenderChar[i]] |= MASK_NAME | MASK_NCNAME; } // remove ':' from allowable MASK_NCNAME_START and MASK_NCNAME chars CHARS[':'] &= ~(MASK_NCNAME_START | MASK_NCNAME); // set Pubid characters for (int i = 0; i < pubidChar.length; i++) { CHARS[pubidChar[i]] |= MASK_PUBID; } for (int i = 0; i < pubidRange.length; i += 2) { for (int j = pubidRange[i]; j <= pubidRange[i + 1]; j++) { CHARS[j] |= MASK_PUBID; } } } // <clinit>() // // Public static methods // /** * Returns true if the specified character is a supplemental character. * * @param c The character to check. */ public static boolean isSupplemental(int c) { return (c >= 0x10000 && c <= 0x10FFFF); } /** * Returns true the supplemental character corresponding to the given * surrogates. * * @param h The high surrogate. * @param l The low surrogate. */ public static int supplemental(char h, char l) { return (h - 0xD800) * 0x400 + (l - 0xDC00) + 0x10000; } /** * Returns the high surrogate of a supplemental character * * @param c The supplemental character to "split". */ public static char highSurrogate(int c) { return (char) (((c - 0x00010000) >> 10) + 0xD800); } /** * Returns the low surrogate of a supplemental character * * @param c The supplemental character to "split". */ public static char lowSurrogate(int c) { return (char) (((c - 0x00010000) & 0x3FF) + 0xDC00); } /** * Returns whether the given character is a high surrogate * * @param c The character to check. */ public static boolean isHighSurrogate(int c) { return (0xD800 <= c && c <= 0xDBFF); } /** * Returns whether the given character is a low surrogate * * @param c The character to check. */ public static boolean isLowSurrogate(int c) { return (0xDC00 <= c && c <= 0xDFFF); } /** * Returns true if the specified character is valid. This method * also checks the surrogate character range from 0x10000 to 0x10FFFF. * <p> * If the program chooses to apply the mask directly to the * <code>CHARS</code> array, then they are responsible for checking * the surrogate character range. * * @param c The character to check. */ public static boolean isValid(int c) { return (c < 0x10000 && (CHARS[c] & MASK_VALID) != 0) || (0x10000 <= c && c <= 0x10FFFF); } // isValid(int):boolean /** * Returns true if the specified character is invalid. * * @param c The character to check. */ public static boolean isInvalid(int c) { return !isValid(c); } // isInvalid(int):boolean /** * Returns true if the specified character can be considered content. * * @param c The character to check. */ public static boolean isContent(int c) { return (c < 0x10000 && (CHARS[c] & MASK_CONTENT) != 0) || (0x10000 <= c && c <= 0x10FFFF); } // isContent(int):boolean /** * Returns true if the specified character can be considered markup. * Markup characters include '&lt;', '&amp;', and '%'. * * @param c The character to check. */ public static boolean isMarkup(int c) { return c == '<' || c == '&' || c == '%'; } // isMarkup(int):boolean /** * Returns true if the specified character is a space character * as defined by production [3] in the XML 1.0 specification. * * @param c The character to check. */ public static boolean isSpace(int c) { return c < 0x10000 && (CHARS[c] & MASK_SPACE) != 0; } // isSpace(int):boolean /** * Returns true if the specified character is a space character * as amdended in the XML 1.1 specification. * * @param c The character to check. */ public static boolean isXML11Space(int c) { return (c < 0x10000 && (CHARS[c] & MASK_SPACE) != 0) || c == 0x85 || c == 0x2028; } // isXML11Space(int):boolean /** * Returns true if the specified character is a valid name start * character as defined by production [5] in the XML 1.0 * specification. * * @param c The character to check. */ public static boolean isNameStart(int c) { return c < 0x10000 && (CHARS[c] & MASK_NAME_START) != 0; } // isNameStart(int):boolean /** * Returns true if the specified character is a valid name * character as defined by production [4] in the XML 1.0 * specification. * * @param c The character to check. */ public static boolean isName(int c) { return c < 0x10000 && (CHARS[c] & MASK_NAME) != 0; } // isName(int):boolean /** * Returns true if the specified character is a valid NCName start * character as defined by production [4] in Namespaces in XML * recommendation. * * @param c The character to check. */ public static boolean isNCNameStart(int c) { return c < 0x10000 && (CHARS[c] & MASK_NCNAME_START) != 0; } // isNCNameStart(int):boolean /** * Returns true if the specified character is a valid NCName * character as defined by production [5] in Namespaces in XML * recommendation. * * @param c The character to check. */ public static boolean isNCName(int c) { return c < 0x10000 && (CHARS[c] & MASK_NCNAME) != 0; } // isNCName(int):boolean /** * Returns true if the specified character is a valid Pubid * character as defined by production [13] in the XML 1.0 * specification. * * @param c The character to check. */ public static boolean isPubid(int c) { return c < 0x10000 && (CHARS[c] & MASK_PUBID) != 0; } // isPubid(int):boolean /* * [5] Name ::= (Letter | '_' | ':') (NameChar)* */ /** * Check to see if a string is a valid Name according to [5] * in the XML 1.0 Recommendation * * @param name string to check * @return true if name is a valid Name */ public static boolean isValidName(String name) { if (name.length() == 0) return false; char ch = name.charAt(0); if( isNameStart(ch) == false) return false; for (int i = 1; i < name.length(); i++ ) { ch = name.charAt(i); if( isName( ch ) == false ){ return false; } } return true; } // isValidName(String):boolean /* * from the namespace rec * [4] NCName ::= (Letter | '_') (NCNameChar)* */ /** * Check to see if a string is a valid NCName according to [4] * from the XML Namespaces 1.0 Recommendation * * @param ncName string to check * @return true if name is a valid NCName */ public static boolean isValidNCName(String ncName) { if (ncName.length() == 0) return false; char ch = ncName.charAt(0); if( isNCNameStart(ch) == false) return false; for (int i = 1; i < ncName.length(); i++ ) { ch = ncName.charAt(i); if( isNCName( ch ) == false ){ return false; } } return true; } // isValidNCName(String):boolean /* * [7] Nmtoken ::= (NameChar)+ */ /** * Check to see if a string is a valid Nmtoken according to [7] * in the XML 1.0 Recommendation * * @param nmtoken string to check * @return true if nmtoken is a valid Nmtoken */ public static boolean isValidNmtoken(String nmtoken) { if (nmtoken.length() == 0) return false; for (int i = 0; i < nmtoken.length(); i++ ) { char ch = nmtoken.charAt(i); if( ! isName( ch ) ){ return false; } } return true; } // isValidName(String):boolean // encodings /** * Returns true if the encoding name is a valid IANA encoding. * This method does not verify that there is a decoder available * for this encoding, only that the characters are valid for an * IANA encoding name. * * @param ianaEncoding The IANA encoding name. */ public static boolean isValidIANAEncoding(String ianaEncoding) { if (ianaEncoding != null) { int length = ianaEncoding.length(); if (length > 0) { char c = ianaEncoding.charAt(0); if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { for (int i = 1; i < length; i++) { c = ianaEncoding.charAt(i); if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.' && c != '_' && c != '-') { return false; } } return true; } } } return false; } // isValidIANAEncoding(String):boolean /** * Returns true if the encoding name is a valid Java encoding. * This method does not verify that there is a decoder available * for this encoding, only that the characters are valid for an * Java encoding name. * * @param javaEncoding The Java encoding name. */ public static boolean isValidJavaEncoding(String javaEncoding) { if (javaEncoding != null) { int length = javaEncoding.length(); if (length > 0) { for (int i = 1; i < length; i++) { char c = javaEncoding.charAt(i); if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.' && c != '_' && c != '-') { return false; } } return true; } } return false; } // isValidIANAEncoding(String):boolean } // class XMLChar
7,628
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/ArrayUtil.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; public class ArrayUtil { private static class ArrayInfo { public Class componentType; public Class arrayType; public int dimension; } public static class NonConvertable { public NonConvertable() { } } /** An object indicating that the conversion is not possible */ public static final NonConvertable NON_CONVERTABLE = new NonConvertable(); /** * Convert ArrayOfT to T[]. * @param obj the object of type ArrayOfT to convert * @param arrayType the destination array type * @return returns the converted array object. * If not convertable the original obj argument is returned. * If the obj is not type of ArrayOfT or the value is null, null is returned. */ public static Object convertObjectToArray(Object obj, Class arrayType) { try { ArrayInfo arri = new ArrayInfo(); boolean rc = internalIsConvertable(obj.getClass(), arri, arrayType); if (rc == false) { return obj; } BeanPropertyDescriptor pd = null; pd = getArrayComponentPD(obj.getClass()); if (pd == null) { return NON_CONVERTABLE; } Object comp = pd.get(obj); if (comp == null) { return null; } int arraylen = 0; if (comp.getClass().isArray()) { arraylen = Array.getLength(comp); } else { return comp; } int[] dims = new int[arri.dimension]; dims[0] = arraylen; Object targetArray = Array.newInstance(arri.componentType, dims); for (int i = 0; i < arraylen; i++) { Object subarray = Array.get(comp, i); Class subarrayClass = arrayType.getComponentType(); Array.set(targetArray, i, convertObjectToArray(subarray, subarrayClass)); } return targetArray; } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } /** * Check if the clazz(perhaps ArrayOfT class) can be converted to T[]. * @param clazz a class of ArrayOfT * @param arrayType an array class (T[]) * @return true if converable, false if not */ public static boolean isConvertable(Class clazz, Class arrayType) { ArrayInfo arrInfo = new ArrayInfo(); return internalIsConvertable(clazz, arrInfo, arrayType); } /** * Check if the clazz(perhaps ArrayOfT class) can be converted to T[]. * @param clazz a class of ArrayOfT * @param arri convert result information * @param arrayType an array class (T[]) * @return true if converable, false if not */ private static boolean internalIsConvertable(Class clazz, ArrayInfo arri, Class arrayType) { BeanPropertyDescriptor pd = null, oldPd = null; if (!arrayType.isArray()) return false; Class destArrCompType = arrayType.getComponentType(); Class src = clazz; int depth = 0; while (true) { pd = getArrayComponentPD(src); if (pd == null) break; depth++; src = pd.getType(); oldPd = pd; if (destArrCompType.isAssignableFrom(src)) break; } if (depth == 0 || oldPd.getType() == null) { return false; } arri.componentType = oldPd.getType(); arri.dimension = depth; Class componentType = oldPd.getType(); int[] dims = new int[depth]; Object array = Array.newInstance(componentType, dims); arri.arrayType = array.getClass(); if (arrayType.isAssignableFrom(arri.arrayType)) return true; else return false; } /** * Gets the BeanPropertyDescriptor of ArrayOfT class's array member. * @param clazz a class of perhaps ArrayOfT type. * @return the BeanPropertyDescriptor. If the clazz is not type of ArrayOfT, null is returned. */ private static BeanPropertyDescriptor getArrayComponentPD(Class clazz) { BeanPropertyDescriptor bpd = null; int count = 0; Class cls = clazz; while (cls != null && cls.getName() != null && !cls.getName().equals("java.lang.Object")) { BeanPropertyDescriptor bpds[] = BeanUtils.getPd(clazz); for (int i = 0; i < bpds.length; i++) { BeanPropertyDescriptor pd = bpds[i]; if (pd.isReadable() && pd.isWriteable() && pd.isIndexed()) { count++; if (count >= 2) return null; else bpd = pd; } } cls = cls.getSuperclass(); } if (count == 1) { return bpd; } else return null; } /** * Gets the dimension of arrayType * @param arrayType an array class * @return the dimension */ public static int getArrayDimension(Class arrayType) { if (!arrayType.isArray()) return 0; int dim = 0; Class compType = arrayType; do { dim++; arrayType = compType; compType = arrayType.getComponentType(); } while (compType.isArray()); return dim; } private static Object createNewInstance(Class cls) throws InstantiationException, IllegalAccessException { Object obj = null; if (!cls.isPrimitive()) obj = cls.newInstance(); else { if (boolean.class.isAssignableFrom(cls)) obj = new Boolean(false); else if (byte.class.isAssignableFrom(cls)) obj = new Byte((byte)0); else if (char.class.isAssignableFrom(cls)) obj = new Character('\u0000'); else if (short.class.isAssignableFrom(cls)) obj = new Short((short)0); else if (int.class.isAssignableFrom(cls)) obj = new Integer(0); else if (long.class.isAssignableFrom(cls)) obj = new Long(0L); else if (float.class.isAssignableFrom(cls)) obj = new Float(0.0F); else if (double.class.isAssignableFrom(cls)) obj = new Double(0.0D); } return obj; } /** * Convert an array object of which type is T[] to ArrayOfT class. * @param array the array object * @param destClass the destination class * @return the object of type destClass if convertable, null if not. */ public static Object convertArrayToObject(Object array, Class destClass) { int dim = getArrayDimension(array.getClass()); if (dim == 0) { return null; } Object dest = null; try { // create the destArray int arraylen = Array.getLength(array); Object destArray = null; Class destComp = null; if (!destClass.isArray()) { dest = destClass.newInstance(); BeanPropertyDescriptor pd = getArrayComponentPD(destClass); if (pd == null) return null; destComp = pd.getType(); destArray = Array.newInstance(destComp, arraylen); pd.set(dest, destArray); } else { destComp = destClass.getComponentType(); dest = Array.newInstance(destComp, arraylen); destArray = dest; } // iniialize the destArray for (int i = 0; i < arraylen; i++) { Array.set(destArray, i, createNewInstance(destComp)); } // set the destArray for (int i = 0; i < arraylen; i++) { Object comp = Array.get(array, i); if(comp == null) continue; if (comp.getClass().isArray()) { Class cls = Array.get(destArray, i).getClass(); Array.set(destArray, i, convertArrayToObject(comp, cls)); } else { Array.set(destArray, i, comp); } } } catch (IllegalAccessException ignore) { return null; } catch (InvocationTargetException ignore) { return null; } catch (InstantiationException ignore) { return null; } return dest; } }
7,629
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/IDKey.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils; /** * Wrap an identity key (System.identityHashCode()) */ public class IDKey { private Object value = null; private int id = 0; /** * Constructor for IDKey * @param _value */ public IDKey(Object _value) { // This is the Object hashcode id = System.identityHashCode(_value); // There have been some cases (bug 11706) that return the // same identity hash code for different objects. So // the value is also added to disambiguate these cases. value = _value; } /** * returns hashcode * @return */ public int hashCode() { return id; } /** * checks if instances are equal * @param other * @return */ public boolean equals(Object other) { if (!(other instanceof IDKey)) { return false; } IDKey idKey = (IDKey) other; if (id != idKey.id) { return false; } // Note that identity equals is used. return value == idKey.value; } }
7,630
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/cache/ClassCache.java
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * 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.axis.utils.cache; import org.apache.axis.utils.ClassUtils; import java.util.Hashtable; /** * A cache class for JavaClass objects, which enables us to quickly reference * methods. * * @author Doug Davis (dug@us.ibm.com) * @author Glen Daniels (gdaniels@apache.org) */ public class ClassCache { Hashtable classCache = new Hashtable(); public ClassCache() { } /** * Register a class in the cache. Creates a new JavaClass object * around the given class, and inserts it into the Hashtable, replacing * any previous entry. * * @param name the name of the class. * @param cls a Java Class. */ public synchronized void registerClass(String name, Class cls) { if (name == null) return; // ??? Should we let this NPE? JavaClass oldClass = (JavaClass) classCache.get(name); if (oldClass != null && oldClass.getJavaClass() == cls) return; classCache.put(name, new JavaClass(cls)); } /** * Remove an entry from the cache. * * @param name the name of the class to remove. */ public synchronized void deregisterClass(String name) { classCache.remove(name); } /** * Query a given class' cache status. * * @param name a class name * @return true if the class is in the cache, false otherwise */ public boolean isClassRegistered(String name) { return (classCache != null && classCache.get(name) != null); } /** * Find the cached JavaClass entry for this class, creating one * if necessary. * @param className name of the class desired * @param cl ClassLoader to use if we need to load the class * @return JavaClass entry */ public JavaClass lookup(String className, ClassLoader cl) throws ClassNotFoundException { if (className == null) { return null; } JavaClass jc = (JavaClass) classCache.get(className); if ((jc == null) && (cl != null)) { // Try to load the class with the specified classloader Class cls = ClassUtils.forName(className, true, cl); jc = new JavaClass(cls); } return jc; } } ;
7,631
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/cache/MethodCache.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils.cache; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.axis.utils.ClassUtils; /** * A cache for methods. * Used to get methods by their signature and stores them in a local * cache for performance reasons. * This class is a singleton - so use getInstance to get an instance of it. * * @author Davanum Srinivas (dims@yahoo.com) * @author Sebastian Dietrich (sebastian.dietrich@anecon.com) */ public class MethodCache { /** * The only instance of this class */ transient private static MethodCache instance; /** * Cache for Methods * In fact this is a map (with classes as keys) of a map (with method-names as keys) */ transient private static ThreadLocal cache; /** * The <i>private</i> constructor for this class. * Use getInstance to get an instance (the only one). */ private MethodCache() { cache = new ThreadLocal(); } /** * Gets the only instance of this class * @return the only instance of this class */ public static MethodCache getInstance() { if (instance == null) { instance = new MethodCache(); } return instance; } /** * Returns the per thread hashmap (for method caching) */ private Map getMethodCache() { Map map = (Map) cache.get(); if (map == null) { map = new HashMap(); cache.set(map); } return map; } /** * Class used as the key for the method cache table. * */ static class MethodKey { /** the name of the method in the cache */ private final String methodName; /** the list of types accepted by the method as arguments */ private final Class[] parameterTypes; /** * Creates a new <code>MethodKey</code> instance. * * @param methodName a <code>String</code> value * @param parameterTypes a <code>Class[]</code> value */ MethodKey(String methodName, Class[] parameterTypes) { this.methodName = methodName; this.parameterTypes = parameterTypes; } public boolean equals(Object other) { MethodKey that = (MethodKey) other; return this.methodName.equals(that.methodName) && Arrays.equals(this.parameterTypes, that.parameterTypes); } public int hashCode() { // allow overloaded methods to collide; we'll sort it out // in equals(). Note that String's implementation of // hashCode already caches its value, so there's no point // in doing so here. return methodName.hashCode(); } } /** used to track methods we've sought but not found in the past */ private static final Object NULL_OBJECT = new Object(); /** * Returns the specified method - if any. * * @param clazz the class to get the method from * @param methodName the name of the method * @param parameterTypes the parameters of the method * @return the found method * * @throws NoSuchMethodException if the method can't be found */ public Method getMethod(Class clazz, String methodName, Class[] parameterTypes) throws NoSuchMethodException { String className = clazz.getName(); Map cache = getMethodCache(); Method method = null; Map methods = null; // Strategy is as follows: // construct a MethodKey to represent the name/arguments // of a method's signature. // // use the name of the class to retrieve a map of that // class' methods // // if a map exists, use the MethodKey to find the // associated value object. if that object is a Method // instance, return it. if that object is anything // else, then it's a reference to our NULL_OBJECT // instance, indicating that we've previously tried // and failed to find a method meeting our requirements, // so return null // // if the map of methods for the class doesn't exist, // or if no value is associated with our key in that map, // then we perform a reflection-based search for the method. // // if we find a method in that search, we store it in the // map using the key; otherwise, we store a reference // to NULL_OBJECT using the key. // Check the cache first. MethodKey key = new MethodKey(methodName, parameterTypes); methods = (Map) cache.get(clazz); if (methods != null) { Object o = methods.get(key); if (o != null) { // cache hit if (o instanceof Method) { // good cache hit return (Method) o; } else { // bad cache hit // we hit the NULL_OBJECT, so this is a search // that previously failed; no point in doing // it again as it is a worst case search // through the entire classpath. return null; } } else { // cache miss: fall through to reflective search } } else { // cache miss: fall through to reflective search } try { method = clazz.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e1) { if (!clazz.isPrimitive() && !className.startsWith("java.") && !className.startsWith("javax.")) { try { Class helper = ClassUtils.forName(className + "_Helper"); method = helper.getMethod(methodName, parameterTypes); } catch (ClassNotFoundException e2) { } } } // first time we've seen this class: set up its method cache if (methods == null) { methods = new HashMap(); cache.put(clazz, methods); } // when no method is found, cache the NULL_OBJECT // so that we don't have to repeat worst-case searches // every time. if (null == method) { methods.put(key, NULL_OBJECT); } else { methods.put(key, method); } return method; } }
7,632
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/cache/JavaClass.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils.cache; import java.lang.reflect.Method; import java.util.Hashtable; import java.io.Serializable; /** * A simple cache of previously loaded classes, and their methods. * * @author Sam Ruby (rubys@us.ibm.com) */ public class JavaClass implements Serializable { private static Hashtable classes = new Hashtable(); private Hashtable methods = new Hashtable(); private Class jc; /** * Find (or create if necessary) a JavaClass associated with a given * class */ public static synchronized JavaClass find(Class jc) { JavaClass result = (JavaClass) classes.get(jc); if (result == null) { result = new JavaClass(jc); classes.put(jc, result); } return result; } /** * Create a cache entry for this java.lang.Class */ public JavaClass(Class jc) { this.jc = jc; classes.put(jc, this); } /** * Return the java.lang.Class associated with this entry */ public Class getJavaClass() { return jc; } /** * Lookup a method based on name. This method returns an array just in * case there is more than one. * @param name name of method */ public Method[] getMethod(String name) { JavaMethod jm = (JavaMethod) methods.get(name); if (jm == null) { methods.put(name, jm=new JavaMethod(jc, name)); } return jm.getMethod(); } };
7,633
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/cache/JavaMethod.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils.cache; import java.lang.reflect.Method; import java.util.Vector; /** * A simple cache of previously loaded methods * * @author Sam Ruby (rubys@us.ibm.com) */ public class JavaMethod { // The list of the methods in the given class with the given name. private Method[] methods = null; /** * Create a cache entry for this java.lang.Class * @param jc java.lang.Class which will be searched for methods * @param name name of the method */ public JavaMethod(Class jc, String name) { Method[] methods = jc.getMethods(); Vector workinglist = new Vector(); // scan for matching names, saving the match if it is unique, // otherwise accumulating a list for (int i=0; i<methods.length; i++) { if (methods[i].getName().equals(name)) { workinglist.addElement(methods[i]); } } // If a list was found, convert it into an array if (workinglist.size() > 0) { this.methods = new Method[workinglist.size()]; workinglist.copyInto(this.methods); } } /** * Lookup a method based on name. This method returns an array just in * case there is more than one. */ public Method[] getMethod() { return methods; } };
7,634
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/bytecode/ChainedParamReader.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.utils.bytecode; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.*; /** * Description: In ParamReader class, user can not get inherited method parameter * from the class they passed in. This is done because of performance. This class * is intended to setup the inheritant chain. If the method could not be found in * the derived class, it will try to search it from super class, if not in the * immedidate super class it will search super class's super class, until it reaches * the root which is java.lang.Object. This is not an eager load since it only * start searching the super class when it is asked to * User: pengyu * Date: Sep 6, 2003 * Time: 11:43:24 PM * */ public class ChainedParamReader { private List chain = new ArrayList(); private List clsChain = new ArrayList(); private Map methodToParamMap = new HashMap(); /** * Process a given class's parameter names * @param cls the class which user wants to get parameter info from * @throws IOException */ public ChainedParamReader(Class cls) throws IOException { ParamReader reader = new ParamReader(cls); chain.add(reader); clsChain.add(cls); } //now I need to create deligate methods /** * return the names of the declared parameters for the given constructor. * If we cannot determine the names, return null. The returned array will * have one name per parameter. The length of the array will be the same * as the length of the Class[] array returned by Constructor.getParameterTypes(). * @param ctor * @return array of names, one per parameter, or null */ public String[] getParameterNames(Constructor ctor) { //there is no need for the constructor chaining. return ((ParamReader) chain.get(0)).getParameterNames(ctor); } /** * return the names of the declared parameters for the given method. * If we cannot determine the names in the current class, we will try * to search its parent class until we reach java.lang.Object. If we * still can not find the method we will return null. The returned array * will have one name per parameter. The length of the array will be the same * as the length of the Class[] array returned by Method.getParameterTypes(). * @param method * @return String[] array of names, one per parameter, or null **/ public String[] getParameterNames(Method method) { //go find the one from the cache first if (methodToParamMap.containsKey(method)) { return (String[]) methodToParamMap.get(method); } String[] ret = null; for (Iterator it = chain.iterator(); it.hasNext();) { ParamReader reader = (ParamReader) it.next(); ret = reader.getParameterNames(method); if (ret != null) { methodToParamMap.put(method, ret); return ret; } } //if we here, it means we need to create new chain. Class cls = (Class) clsChain.get(chain.size() - 1); while (cls.getSuperclass() != null) { Class superClass = cls.getSuperclass(); try { ParamReader _reader = new ParamReader(superClass); chain.add(_reader); clsChain.add(cls); ret = _reader.getParameterNames(method); if (ret != null) { //we found it so just return it. methodToParamMap.put(method, ret); return ret; } } catch (IOException e) { //can not find the super class in the class path, abort here return null; } } methodToParamMap.put(method, ret); return null; } }
7,635
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/bytecode/ParamNameExtractor.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.utils.bytecode; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * This class retieves function parameter names from bytecode built with * debugging symbols. Used as a last resort when creating WSDL. * * @author <a href="mailto:tomj@macromedia.com">Tom Jordahl</a> */ public class ParamNameExtractor { protected static Log log = LogFactory.getLog(ParamNameExtractor.class.getName()); /** * Retrieve a list of function parameter names from a method * Returns null if unable to read parameter names (i.e. bytecode not * built with debug). */ public static String[] getParameterNamesFromDebugInfo(Method method) { // Don't worry about it if there are no params. int numParams = method.getParameterTypes().length; if (numParams == 0) return null; // get declaring class Class c = method.getDeclaringClass(); // Don't worry about it if the class is a Java dynamic proxy if(Proxy.isProxyClass(c)) { return null; } try { // get a parameter reader ParamReader pr = new ParamReader(c); // get the paramter names String[] names = pr.getParameterNames(method); return names; } catch (IOException e) { // log it and leave log.info(Messages.getMessage("error00") + ":" + e); return null; } } }
7,636
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/bytecode/ClassReader.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.utils.bytecode; import org.apache.axis.utils.Messages; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * This is the class file reader for obtaining the parameter names * for declared methods in a class. The class must have debugging * attributes for us to obtain this information. <p> * * This does not work for inherited methods. To obtain parameter * names for inherited methods, you must use a paramReader for the * class that originally declared the method. <p> * * don't get tricky, it's the bare minimum. Instances of this class * are not threadsafe -- don't share them. <p> * * @author Edwin Smith, Macromedia */ public class ClassReader extends ByteArrayInputStream { // constants values that appear in java class files, // from jvm spec 2nd ed, section 4.4, pp 103 private static final int CONSTANT_Class = 7; private static final int CONSTANT_Fieldref = 9; private static final int CONSTANT_Methodref = 10; private static final int CONSTANT_InterfaceMethodref = 11; private static final int CONSTANT_String = 8; private static final int CONSTANT_Integer = 3; private static final int CONSTANT_Float = 4; private static final int CONSTANT_Long = 5; private static final int CONSTANT_Double = 6; private static final int CONSTANT_NameAndType = 12; private static final int CONSTANT_Utf8 = 1; /*java 8 9 10 11 new tokens https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-4.html*/ private static final int CONSTANT_MethodHandle = 15; private static final int CONSTANT_MethodType = 16; private static final int CONSTANT_Dynamic = 17; private static final int CONSTANT_InvokeDynamic = 18; private static final int CONSTANT_Module = 19; private static final int CONSTANT_Package = 20; /*end of ava 8 9 10 11 new tokens*/ /** * the constant pool. constant pool indices in the class file * directly index into this array. The value stored in this array * is the position in the class file where that constant begins. */ private int[] cpoolIndex; private Object[] cpool; private Map attrMethods; /** * load the bytecode for a given class, by using the class's defining * classloader and assuming that for a class named P.C, the bytecodes are * in a resource named /P/C.class. * @param c the class of interest * @return a byte array containing the bytecode * @throws IOException */ protected static byte[] getBytes(Class c) throws IOException { InputStream fin = c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"); if (fin == null) { throw new IOException( Messages.getMessage("cantLoadByecode", c.getName())); } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int actual; do { actual = fin.read(buf); if (actual > 0) { out.write(buf, 0, actual); } } while (actual > 0); return out.toByteArray(); } finally { fin.close(); } } static String classDescriptorToName(String desc) { return desc.replace('/', '.'); } protected static Map findAttributeReaders(Class c) { HashMap map = new HashMap(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { String name = methods[i].getName(); if (name.startsWith("read") && methods[i].getReturnType() == void.class) { map.put(name.substring(4), methods[i]); } } return map; } protected static String getSignature(Member method, Class[] paramTypes) { // compute the method descriptor StringBuffer b = new StringBuffer((method instanceof Method) ? method.getName() : "<init>"); b.append('('); for (int i = 0; i < paramTypes.length; i++) { addDescriptor(b, paramTypes[i]); } b.append(')'); if (method instanceof Method) { addDescriptor(b, ((Method) method).getReturnType()); } else if (method instanceof Constructor) { addDescriptor(b, void.class); } return b.toString(); } private static void addDescriptor(StringBuffer b, Class c) { if (c.isPrimitive()) { if (c == void.class) b.append('V'); else if (c == int.class) b.append('I'); else if (c == boolean.class) b.append('Z'); else if (c == byte.class) b.append('B'); else if (c == short.class) b.append('S'); else if (c == long.class) b.append('J'); else if (c == char.class) b.append('C'); else if (c == float.class) b.append('F'); else if (c == double.class) b.append('D'); } else if (c.isArray()) { b.append('['); addDescriptor(b, c.getComponentType()); } else { b.append('L').append(c.getName().replace('.', '/')).append(';'); } } /** * @return the next unsigned 16 bit value */ protected final int readShort() { return (read() << 8) | read(); } /** * @return the next signed 32 bit value */ protected final int readInt() { return (read() << 24) | (read() << 16) | (read() << 8) | read(); } /** * skip n bytes in the input stream. */ protected void skipFully(int n) throws IOException { while (n > 0) { int c = (int) skip(n); if (c <= 0) throw new EOFException(Messages.getMessage("unexpectedEOF00")); n -= c; } } protected final Member resolveMethod(int index) throws IOException, ClassNotFoundException, NoSuchMethodException { int oldPos = pos; try { Member m = (Member) cpool[index]; if (m == null) { pos = cpoolIndex[index]; Class owner = resolveClass(readShort()); NameAndType nt = resolveNameAndType(readShort()); String signature = nt.name + nt.type; if (nt.name.equals("<init>")) { Constructor[] ctors = owner.getConstructors(); for (int i = 0; i < ctors.length; i++) { String sig = getSignature(ctors[i], ctors[i].getParameterTypes()); if (sig.equals(signature)) { cpool[index] = m = ctors[i]; return m; } } } else { Method[] methods = owner.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String sig = getSignature(methods[i], methods[i].getParameterTypes()); if (sig.equals(signature)) { cpool[index] = m = methods[i]; return m; } } } throw new NoSuchMethodException(signature); } return m; } finally { pos = oldPos; } } protected final Field resolveField(int i) throws IOException, ClassNotFoundException, NoSuchFieldException { int oldPos = pos; try { Field f = (Field) cpool[i]; if (f == null) { pos = cpoolIndex[i]; Class owner = resolveClass(readShort()); NameAndType nt = resolveNameAndType(readShort()); cpool[i] = f = owner.getDeclaredField(nt.name); } return f; } finally { pos = oldPos; } } private static class NameAndType { String name; String type; public NameAndType(String name, String type) { this.name = name; this.type = type; } } protected final NameAndType resolveNameAndType(int i) throws IOException { int oldPos = pos; try { NameAndType nt = (NameAndType) cpool[i]; if (nt == null) { pos = cpoolIndex[i]; String name = resolveUtf8(readShort()); String type = resolveUtf8(readShort()); cpool[i] = nt = new NameAndType(name, type); } return nt; } finally { pos = oldPos; } } protected final Class resolveClass(int i) throws IOException, ClassNotFoundException { int oldPos = pos; try { Class c = (Class) cpool[i]; if (c == null) { pos = cpoolIndex[i]; String name = resolveUtf8(readShort()); cpool[i] = c = Class.forName(classDescriptorToName(name)); } return c; } finally { pos = oldPos; } } protected final String resolveUtf8(int i) throws IOException { int oldPos = pos; try { String s = (String) cpool[i]; if (s == null) { pos = cpoolIndex[i]; int len = readShort(); skipFully(len); cpool[i] = s = new String(buf, pos - len, len, "utf-8"); } return s; } finally { pos = oldPos; } } protected final void readCpool() throws IOException { int count = readShort(); // cpool count cpoolIndex = new int[count]; cpool = new Object[count]; for (int i = 1; i < count; i++) { int c = read(); cpoolIndex[i] = super.pos; switch (c) // constant pool tag { case CONSTANT_Fieldref: case CONSTANT_Methodref: case CONSTANT_InterfaceMethodref: case CONSTANT_NameAndType: readShort(); // class index or (12) name index // fall through case CONSTANT_Class: case CONSTANT_String: readShort(); // string index or class index break; case CONSTANT_Long: case CONSTANT_Double: readInt(); // hi-value // see jvm spec section 4.4.5 - double and long cpool // entries occupy two "slots" in the cpool table. i++; // fall through case CONSTANT_Integer: case CONSTANT_Float: readInt(); // value break; case CONSTANT_Utf8: int len = readShort(); skipFully(len); break; case CONSTANT_MethodHandle: read(); // reference kind readShort(); // reference index break; case CONSTANT_MethodType: readShort(); // descriptor index break; case CONSTANT_Dynamic: readShort(); // bootstrap method attr index readShort(); // name and type index break; case CONSTANT_InvokeDynamic: readShort(); // bootstrap method attr index readShort(); // name and type index break; default: // corrupt class file throw new IllegalStateException("Error looking for paramter names in bytecode: unexpected bytes in file, tag:"+c); } } } protected final void skipAttributes() throws IOException { int count = readShort(); for (int i = 0; i < count; i++) { readShort(); // name index skipFully(readInt()); } } /** * read an attributes array. the elements of a class file that * can contain attributes are: fields, methods, the class itself, * and some other types of attributes. */ protected final void readAttributes() throws IOException { int count = readShort(); for (int i = 0; i < count; i++) { int nameIndex = readShort(); // name index int attrLen = readInt(); int curPos = pos; String attrName = resolveUtf8(nameIndex); Method m = (Method) attrMethods.get(attrName); if (m != null) { try { m.invoke(this, new Object[]{}); } catch (IllegalAccessException e) { pos = curPos; skipFully(attrLen); } catch (InvocationTargetException e) { try { throw e.getTargetException(); } catch (Error ex) { throw ex; } catch (RuntimeException ex) { throw ex; } catch (IOException ex) { throw ex; } catch (Throwable ex) { pos = curPos; skipFully(attrLen); } } } else { // don't care what attribute this is skipFully(attrLen); } } } /** * read a code attribute * @throws IOException */ public void readCode() throws IOException { readShort(); // max stack readShort(); // max locals skipFully(readInt()); // code skipFully(8 * readShort()); // exception table // read the code attributes (recursive). This is where // we will find the LocalVariableTable attribute. readAttributes(); } protected ClassReader(byte buf[], Map attrMethods) { super(buf); this.attrMethods = attrMethods; } }
7,637
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/utils/bytecode/ParamReader.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.utils.bytecode; import org.apache.axis.utils.Messages; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; /** * This is the class file reader for obtaining the parameter names * for declared methods in a class. The class must have debugging * attributes for us to obtain this information. <p> * * This does not work for inherited methods. To obtain parameter * names for inherited methods, you must use a paramReader for the * class that originally declared the method. <p> * * don't get tricky, it's the bare minimum. Instances of this class * are not threadsafe -- don't share them. <p> * * @author Edwin Smith, Macromedia */ public class ParamReader extends ClassReader { private String methodName; private Map methods = new HashMap(); private Class[] paramTypes; /** * process a class file, given it's class. We'll use the defining * classloader to locate the bytecode. * @param c * @throws IOException */ public ParamReader(Class c) throws IOException { this(getBytes(c)); } /** * process the given class bytes directly. * @param b * @throws IOException */ public ParamReader(byte[] b) throws IOException { super(b, findAttributeReaders(ParamReader.class)); // check the magic number if (readInt() != 0xCAFEBABE) { // not a class file! throw new IOException(Messages.getMessage("badClassFile00")); } readShort(); // minor version readShort(); // major version readCpool(); // slurp in the constant pool readShort(); // access flags readShort(); // this class name readShort(); // super class name int count = readShort(); // ifaces count for (int i = 0; i < count; i++) { readShort(); // interface index } count = readShort(); // fields count for (int i = 0; i < count; i++) { readShort(); // access flags readShort(); // name index readShort(); // descriptor index skipAttributes(); // field attributes } count = readShort(); // methods count for (int i = 0; i < count; i++) { readShort(); // access flags int m = readShort(); // name index String name = resolveUtf8(m); int d = readShort(); // descriptor index this.methodName = name + resolveUtf8(d); readAttributes(); // method attributes } } public void readCode() throws IOException { readShort(); // max stack int maxLocals = readShort(); // max locals MethodInfo info = new MethodInfo(maxLocals); if (methods != null && methodName != null) { methods.put(methodName, info); } skipFully(readInt()); // code skipFully(8 * readShort()); // exception table // read the code attributes (recursive). This is where // we will find the LocalVariableTable attribute. readAttributes(); } /** * return the names of the declared parameters for the given constructor. * If we cannot determine the names, return null. The returned array will * have one name per parameter. The length of the array will be the same * as the length of the Class[] array returned by Constructor.getParameterTypes(). * @param ctor * @return String[] array of names, one per parameter, or null */ public String[] getParameterNames(Constructor ctor) { paramTypes = ctor.getParameterTypes(); return getParameterNames(ctor, paramTypes); } /** * return the names of the declared parameters for the given method. * If we cannot determine the names, return null. The returned array will * have one name per parameter. The length of the array will be the same * as the length of the Class[] array returned by Method.getParameterTypes(). * @param method * @return String[] array of names, one per parameter, or null */ public String[] getParameterNames(Method method) { paramTypes = method.getParameterTypes(); return getParameterNames(method, paramTypes); } protected String[] getParameterNames(Member member,Class [] paramTypes) { // look up the names for this method MethodInfo info = (MethodInfo) methods.get(getSignature(member, paramTypes)); // we know all the local variable names, but we only need to return // the names of the parameters. if (info != null) { String[] paramNames = new String[paramTypes.length]; int j = Modifier.isStatic(member.getModifiers()) ? 0 : 1; boolean found = false; // did we find any non-null names for (int i = 0; i < paramNames.length; i++) { if (info.names[j] != null) { found = true; paramNames[i] = info.names[j]; } j++; if (paramTypes[i] == double.class || paramTypes[i] == long.class) { // skip a slot for 64bit params j++; } } if (found) { return paramNames; } else { return null; } } else { return null; } } private static class MethodInfo { String[] names; int maxLocals; public MethodInfo(int maxLocals) { this.maxLocals = maxLocals; names = new String[maxLocals]; } } private MethodInfo getMethodInfo() { MethodInfo info = null; if (methods != null && methodName != null) { info = (MethodInfo) methods.get(methodName); } return info; } /** * this is invoked when a LocalVariableTable attribute is encountered. * @throws IOException */ public void readLocalVariableTable() throws IOException { int len = readShort(); // table length MethodInfo info = getMethodInfo(); for (int j = 0; j < len; j++) { readShort(); // start pc readShort(); // length int nameIndex = readShort(); // name_index readShort(); // descriptor_index int index = readShort(); // local index if (info != null) { info.names[index] = resolveUtf8(nameIndex); } } } }
7,638
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAPConnectionImpl.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import org.apache.axis.Message; import org.apache.axis.attachments.Attachments; import org.apache.axis.client.Call; import org.apache.axis.utils.Messages; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.soap.MimeHeaders; import java.util.Iterator; /** * SOAP Connection implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class SOAPConnectionImpl extends javax.xml.soap.SOAPConnection { private boolean closed = false; private Integer timeout = null; /** * get the timeout value * @return */ public Integer getTimeout() { return timeout; } /** * set the timeout value * @param timeout */ public void setTimeout(Integer timeout) { this.timeout = timeout; } /** * Sends the given message to the specified endpoint and * blocks until it has returned the response. * @param request the <CODE>SOAPMessage</CODE> * object to be sent * @param endpoint a <CODE>URLEndpoint</CODE> * object giving the URL to which the message should be * sent * @return the <CODE>SOAPMessage</CODE> object that is the * response to the message that was sent * @throws SOAPException if there is a SOAP error */ public SOAPMessage call(SOAPMessage request, Object endpoint) throws SOAPException { if(closed){ throw new SOAPException(Messages.getMessage("connectionClosed00")); } try { Call call = new Call(endpoint.toString()); ((org.apache.axis.Message)request).setMessageContext(call.getMessageContext()); Attachments attachments = ((org.apache.axis.Message) request).getAttachmentsImpl(); if (attachments != null) { Iterator iterator = attachments.getAttachments().iterator(); while (iterator.hasNext()) { Object attachment = iterator.next(); call.addAttachmentPart(attachment); } } String soapActionURI = checkForSOAPActionHeader(request); if (soapActionURI != null) call.setSOAPActionURI(soapActionURI); call.setTimeout(timeout); call.setReturnClass(SOAPMessage.class); call.setProperty(Call.CHECK_MUST_UNDERSTAND,Boolean.FALSE); call.invoke((Message) request); return call.getResponseMessage(); } catch (java.net.MalformedURLException mue){ throw new SOAPException(mue); } catch (org.apache.axis.AxisFault af){ return new Message(af); } } /** * Checks whether the request has an associated SOAPAction MIME header * and returns its value. * @param request the message to check * @return the value of any associated SOAPAction MIME header or null * if there is no such header. */ private String checkForSOAPActionHeader(SOAPMessage request) { MimeHeaders hdrs = request.getMimeHeaders(); if (hdrs != null) { String[] saHdrs = hdrs.getHeader("SOAPAction"); if (saHdrs != null && saHdrs.length > 0) return saHdrs[0]; } return null; } /** * Closes this <CODE>SOAPConnection</CODE> object. * @throws SOAPException if there is a SOAP error */ public void close() throws SOAPException { if(closed){ throw new SOAPException(Messages.getMessage("connectionClosed00")); } closed = true; } }
7,639
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAPFactoryImpl.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import org.apache.axis.message.Detail; import org.apache.axis.message.MessageElement; import org.apache.axis.message.PrefixedQName; import javax.xml.soap.Name; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; /** * SOAP Element Factory implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class SOAPFactoryImpl extends javax.xml.soap.SOAPFactory { /** * Create a <CODE>SOAPElement</CODE> object initialized with * the given <CODE>Name</CODE> object. * @param name a <CODE>Name</CODE> object with * the XML name for the new element * @return the new <CODE>SOAPElement</CODE> object that was * created * @throws SOAPException if there is an error in * creating the <CODE>SOAPElement</CODE> object */ public SOAPElement createElement(Name name) throws SOAPException { return new MessageElement(name); } /** * Create a <CODE>SOAPElement</CODE> object initialized with * the given local name. * @param localName a <CODE>String</CODE> giving * the local name for the new element * @return the new <CODE>SOAPElement</CODE> object that was * created * @throws SOAPException if there is an error in * creating the <CODE>SOAPElement</CODE> object */ public SOAPElement createElement(String localName) throws SOAPException { return new MessageElement("",localName); } /** * Create a new <CODE>SOAPElement</CODE> object with the * given local name, prefix and uri. * @param localName a <CODE>String</CODE> giving * the local name for the new element * @param prefix the prefix for this <CODE> * SOAPElement</CODE> * @param uri a <CODE>String</CODE> giving the * URI of the namespace to which the new element * belongs * @return the new <CODE>SOAPElement</CODE> object that was * created * @throws SOAPException if there is an error in * creating the <CODE>SOAPElement</CODE> object */ public SOAPElement createElement( String localName, String prefix, String uri) throws SOAPException { return new MessageElement(localName, prefix, uri); } public javax.xml.soap.Detail createDetail() throws SOAPException { return new Detail(); } public Name createName(String localName, String prefix, String uri) throws SOAPException { return new PrefixedQName(uri,localName,prefix); } public Name createName(String localName) throws SOAPException { return new PrefixedQName("",localName,""); } }
7,640
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/MessageFactoryImpl.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import org.apache.axis.Message; import org.apache.axis.message.SOAPEnvelope; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import java.io.IOException; import java.io.InputStream; /** * Message Factory implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class MessageFactoryImpl extends javax.xml.soap.MessageFactory { /** * Creates a new <CODE>SOAPMessage</CODE> object with the * default <CODE>SOAPPart</CODE>, <CODE>SOAPEnvelope</CODE>, * <CODE>SOAPBody</CODE>, and <CODE>SOAPHeader</CODE> objects. * Profile-specific message factories can choose to * prepopulate the <CODE>SOAPMessage</CODE> object with * profile-specific headers. * * <P>Content can be added to this message's <CODE> * SOAPPart</CODE> object, and the message can be sent "as is" * when a message containing only a SOAP part is sufficient. * Otherwise, the <CODE>SOAPMessage</CODE> object needs to * create one or more <CODE>AttachmentPart</CODE> objects and * add them to itself. Any content that is not in XML format * must be in an <CODE>AttachmentPart</CODE> object.</P> * @return a new <CODE>SOAPMessage</CODE> object * @throws SOAPException if a SOAP error occurs */ public SOAPMessage createMessage() throws SOAPException { SOAPEnvelope env = new SOAPEnvelope(); env.setSAAJEncodingCompliance(true); Message message = new Message(env); message.setMessageType(Message.REQUEST); return message; } /** * Internalizes the contents of the given <CODE> * InputStream</CODE> object into a new <CODE>SOAPMessage</CODE> * object and returns the <CODE>SOAPMessage</CODE> object. * @param mimeheaders the transport-specific headers * passed to the message in a transport-independent fashion * for creation of the message * @param inputstream the <CODE>InputStream</CODE> object * that contains the data for a message * @return a new <CODE>SOAPMessage</CODE> object containing the * data from the given <CODE>InputStream</CODE> object * @throws IOException if there is a * problem in reading data from the input stream * @throws SOAPException if the message is invalid */ public SOAPMessage createMessage( MimeHeaders mimeheaders, InputStream inputstream) throws IOException, SOAPException { Message message = new Message(inputstream, false, mimeheaders); message.setMessageType(Message.REQUEST); return message; } }
7,641
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAPConnectionFactoryImpl.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPException; /** * SOAP Connection Factory implementation * * @author Davanum Srinivas (dims@yahoo.com) */ public class SOAPConnectionFactoryImpl extends javax.xml.soap.SOAPConnectionFactory { /** * Create a new <CODE>SOAPConnection</CODE>. * @return the new <CODE>SOAPConnection</CODE> object. * @throws SOAPException if there was an exception * creating the <CODE>SOAPConnection</CODE> object. */ public SOAPConnection createConnection() throws SOAPException { return new SOAPConnectionImpl(); } }
7,642
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAP12Constants.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import org.apache.axis.Constants; import javax.xml.namespace.QName; /** * SOAP 1.2 constants * * @author Glen Daniels (gdaniels@apache.org) * @author Andras Avar (andras.avar@nokia.com) */ public class SOAP12Constants implements SOAPConstants { private static QName headerQName = new QName(Constants.URI_SOAP12_ENV, Constants.ELEM_HEADER); private static QName bodyQName = new QName(Constants.URI_SOAP12_ENV, Constants.ELEM_BODY); private static QName faultQName = new QName(Constants.URI_SOAP12_ENV, Constants.ELEM_FAULT); private static QName roleQName = new QName(Constants.URI_SOAP12_ENV, Constants.ATTR_ROLE); // Public constants for SOAP 1.2 /** MessageContext property name for webmethod */ public static final String PROP_WEBMETHOD = "soap12.webmethod"; public String getEnvelopeURI() { return Constants.URI_SOAP12_ENV; } public String getEncodingURI() { return Constants.URI_SOAP12_ENC; } public QName getHeaderQName() { return headerQName; } public QName getBodyQName() { return bodyQName; } public QName getFaultQName() { return faultQName; } /** * Obtain the QName for the role attribute (actor/role) */ public QName getRoleAttributeQName() { return roleQName; } /** * Obtain the MIME content type */ public String getContentType() { return "application/soap+xml"; } /** * Obtain the "next" role/actor URI */ public String getNextRoleURI() { return Constants.URI_SOAP12_NEXT_ROLE; } /** * Obtain the ref attribute name */ public String getAttrHref() { return Constants.ATTR_REF; } /** * Obtain the item type name of an array */ public String getAttrItemType() { return Constants.ATTR_ITEM_TYPE; } /** * Obtain the Qname of VersionMismatch fault code */ public QName getVerMismatchFaultCodeQName() { return Constants.FAULT_SOAP12_VERSIONMISMATCH; } /** * Obtain the Qname of Mustunderstand fault code */ public QName getMustunderstandFaultQName() { return Constants.FAULT_SOAP12_MUSTUNDERSTAND; } /** * Obtain the QName of the SOAP array type */ public QName getArrayType() { return Constants.SOAP_ARRAY12; } }
7,643
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAPConstants.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import javax.xml.namespace.QName; import java.io.Serializable; /** * An interface definining SOAP constants. This allows various parts of the * engine to avoid hardcoding dependence on a particular SOAP version and its * associated URIs, etc. * * This might be fleshed out later to encapsulate factories for behavioral * objects which act differently depending on the SOAP version, but for now * it just supplies common namespaces + QNames. * * @author Glen Daniels (gdaniels@apache.org) * @author Andras Avar (andras.avar@nokia.com) */ public interface SOAPConstants extends Serializable { /** SOAP 1.1 constants - thread-safe and shared */ public SOAP11Constants SOAP11_CONSTANTS = new SOAP11Constants(); /** SOAP 1.2 constants - thread-safe and shared */ public SOAP12Constants SOAP12_CONSTANTS = new SOAP12Constants(); /** * Obtain the envelope namespace for this version of SOAP */ public String getEnvelopeURI(); /** * Obtain the encoding namespace for this version of SOAP */ public String getEncodingURI(); /** * Obtain the QName for the Fault element */ public QName getFaultQName(); /** * Obtain the QName for the Header element */ public QName getHeaderQName(); /** * Obtain the QName for the Body element */ public QName getBodyQName(); /** * Obtain the QName for the role attribute (actor/role) */ public QName getRoleAttributeQName(); /** * Obtain the MIME content type */ public String getContentType(); /** * Obtain the "next" role/actor URI */ public String getNextRoleURI(); /** * Obtain the href attribute name */ public String getAttrHref(); /** * Obtain the item type name of an array */ public String getAttrItemType(); /** * Obtain the Qname of VersionMismatch fault code */ public QName getVerMismatchFaultCodeQName(); /** * Obtain the Qname of Mustunderstand fault code */ public QName getMustunderstandFaultQName(); /** * Obtain the QName of the SOAP array type */ QName getArrayType(); }
7,644
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/soap/SOAP11Constants.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.soap; import javax.xml.namespace.QName; import org.apache.axis.Constants; /** * SOAP 1.1 constants * * @author Glen Daniels (gdaniels@apache.org) * @author Andras Avar (andras.avar@nokia.com) */ public class SOAP11Constants implements SOAPConstants { private static QName headerQName = new QName(Constants.URI_SOAP11_ENV, Constants.ELEM_HEADER); private static QName bodyQName = new QName(Constants.URI_SOAP11_ENV, Constants.ELEM_BODY); private static QName faultQName = new QName(Constants.URI_SOAP11_ENV, Constants.ELEM_FAULT); private static QName roleQName = new QName(Constants.URI_SOAP11_ENV, Constants.ATTR_ACTOR); public String getEnvelopeURI() { return Constants.URI_SOAP11_ENV; } public String getEncodingURI() { return Constants.URI_SOAP11_ENC; } public QName getHeaderQName() { return headerQName; } public QName getBodyQName() { return bodyQName; } public QName getFaultQName() { return faultQName; } /** * Obtain the QName for the role attribute (actor/role) */ public QName getRoleAttributeQName() { return roleQName; } /** * Obtain the MIME content type */ public String getContentType() { return "text/xml"; } /** * Obtain the "next" role/actor URI */ public String getNextRoleURI() { return Constants.URI_SOAP11_NEXT_ACTOR; } /** * Obtain the ref attribute name */ public String getAttrHref() { return Constants.ATTR_HREF; } /** * Obtain the item type name of an array */ public String getAttrItemType() { return Constants.ATTR_ARRAY_TYPE; } /** * Obtain the Qname of VersionMismatch fault code */ public QName getVerMismatchFaultCodeQName() { return Constants.FAULT_VERSIONMISMATCH; } /** * Obtain the Qname of Mustunderstand fault code */ public QName getMustunderstandFaultQName() { return Constants.FAULT_MUSTUNDERSTAND; } /** * Obtain the QName of the SOAP array type */ public QName getArrayType() { return Constants.SOAP_ARRAY; } }
7,645
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/schema/SchemaVersion1999.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.schema; import org.apache.axis.Constants; import org.apache.axis.encoding.TypeMappingImpl; import org.apache.axis.encoding.ser.CalendarDeserializerFactory; import org.apache.axis.encoding.ser.CalendarSerializerFactory; import javax.xml.namespace.QName; /** * 1999 Schema characteristics. * * @author Glen Daniels (gdaniels@apache.org) */ public class SchemaVersion1999 implements SchemaVersion { public static QName QNAME_NIL = new QName(Constants.URI_1999_SCHEMA_XSI, "null"); /** * Package-access constructor - access this through SchemaVersion * constants. */ SchemaVersion1999() { } /** * Get the appropriate QName for the "null"/"nil" attribute for this * Schema version. * @return {http://www.w3.org/1999/XMLSchema-instance}null */ public QName getNilQName() { return QNAME_NIL; } /** * The XSI URI * @return the XSI URI */ public String getXsiURI() { return Constants.URI_1999_SCHEMA_XSI; } /** * The XSD URI * @return the XSD URI */ public String getXsdURI() { return Constants.URI_1999_SCHEMA_XSD; } /** * Register the schema specific type mappings */ public void registerSchemaSpecificTypes(TypeMappingImpl tm) { // Register the timeInstant type tm.register(java.util.Calendar.class, Constants.XSD_TIMEINSTANT1999, new CalendarSerializerFactory(java.util.Calendar.class, Constants.XSD_TIMEINSTANT1999), new CalendarDeserializerFactory(java.util.Calendar.class, Constants.XSD_TIMEINSTANT1999)); } }
7,646
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/schema/SchemaVersion2000.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.schema; import org.apache.axis.Constants; import org.apache.axis.encoding.TypeMappingImpl; import org.apache.axis.encoding.ser.CalendarDeserializerFactory; import org.apache.axis.encoding.ser.CalendarSerializerFactory; import javax.xml.namespace.QName; /** * 2000 Schema characteristics. * * @author Glen Daniels (gdaniels@apache.org) */ public class SchemaVersion2000 implements SchemaVersion { public static QName QNAME_NIL = new QName(Constants.URI_2000_SCHEMA_XSI, "null"); /** * Package-access constructor - access this through SchemaVersion * constants. */ SchemaVersion2000() { } /** * Get the appropriate QName for the "null"/"nil" attribute for this * Schema version. * @return {http://www.w3.org/2000/10/XMLSchema-instance}null */ public QName getNilQName() { return QNAME_NIL; } /** * The XSI URI * @return the XSI URI */ public String getXsiURI() { return Constants.URI_2000_SCHEMA_XSI; } /** * The XSD URI * @return the XSD URI */ public String getXsdURI() { return Constants.URI_2000_SCHEMA_XSD; } /** * Register the schema specific type mappings */ public void registerSchemaSpecificTypes(TypeMappingImpl tm) { // Register the timeInstant type tm.register(java.util.Calendar.class, Constants.XSD_TIMEINSTANT2000, new CalendarSerializerFactory(java.util.Calendar.class, Constants.XSD_TIMEINSTANT2000), new CalendarDeserializerFactory(java.util.Calendar.class, Constants.XSD_TIMEINSTANT2000)); } }
7,647
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/schema/SchemaVersion2001.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.schema; import org.apache.axis.Constants; import org.apache.axis.encoding.TypeMappingImpl; import org.apache.axis.encoding.ser.CalendarDeserializerFactory; import org.apache.axis.encoding.ser.CalendarSerializerFactory; import javax.xml.namespace.QName; /** * 2001 Schema characteristics. * * @author Glen Daniels (gdaniels@apache.org) */ public class SchemaVersion2001 implements SchemaVersion { public static QName QNAME_NIL = new QName(Constants.URI_2001_SCHEMA_XSI, "nil"); /** * Package-access constructor - access this through SchemaVersion * constants. */ SchemaVersion2001() { } /** * Get the appropriate QName for the "null"/"nil" attribute for this * Schema version. * @return {http://www.w3.org/2001/XMLSchema-instance}nil */ public QName getNilQName() { return QNAME_NIL; } /** * The XSI URI * @return the XSI URI */ public String getXsiURI() { return Constants.URI_2001_SCHEMA_XSI; } /** * The XSD URI * @return the XSD URI */ public String getXsdURI() { return Constants.URI_2001_SCHEMA_XSD; } /** * Register the schema specific type mappings */ public void registerSchemaSpecificTypes(TypeMappingImpl tm) { // This mapping will convert a Java 'Date' type to a dateTime tm.register(java.util.Date.class, Constants.XSD_DATETIME, new CalendarSerializerFactory(java.util.Date.class, Constants.XSD_DATETIME), new CalendarDeserializerFactory(java.util.Date.class, Constants.XSD_DATETIME) ); // This is the preferred mapping per JAX-RPC. // Last one registered take priority tm.register(java.util.Calendar.class, Constants.XSD_DATETIME, new CalendarSerializerFactory(java.util.Calendar.class, Constants.XSD_DATETIME), new CalendarDeserializerFactory(java.util.Calendar.class, Constants.XSD_DATETIME) ); } }
7,648
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/schema/SchemaVersion.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.schema; import org.apache.axis.encoding.TypeMappingImpl; import javax.xml.namespace.QName; import java.io.Serializable; /** * The SchemaVersion interface allows us to abstract out the differences * between the 1999, 2000, and 2001 versions of XML Schema. * * @author Glen Daniels (gdaniels@apache.org) */ public interface SchemaVersion extends Serializable { public static SchemaVersion SCHEMA_1999 = new SchemaVersion1999(); public static SchemaVersion SCHEMA_2000 = new SchemaVersion2000(); public static SchemaVersion SCHEMA_2001 = new SchemaVersion2001(); /** * Get the appropriate QName for the "null"/"nil" attribute for this * Schema version. * @return the appropriate "null"/"nil" QName */ public QName getNilQName(); /** * The XSI URI * @return the XSI URI */ public String getXsiURI(); /** * The XSD URI * @return the XSD URI */ public String getXsdURI(); /** * Register the schema specific type mappings */ public void registerSchemaSpecificTypes(TypeMappingImpl tm); }
7,649
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/SocketFactory.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.components.net; import java.net.Socket; /** * Socket factory. * @author Davanum Srinivas (dims@yahoo.com) */ public interface SocketFactory { /** * Create a socket * * @param host * @param port * @param otherHeaders * @param useFullURL * * @return * * @throws Exception */ public Socket create(String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception; }
7,650
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/BooleanHolder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; /** * hold a boolean value. * @author Davanum Srinivas (dims@yahoo.com) */ public class BooleanHolder { /** Field value */ public boolean value; /** * Constructor BooleanHolder * * @param value */ public BooleanHolder(boolean value) { this.value = value; } }
7,651
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/SunJSSESocketFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.Security; import java.util.Hashtable; import com.sun.net.ssl.SSLContext; /** * SSL socket factory. It _requires_ a valid RSA key and * JSSE. (borrowed code from tomcat) * * @author Davanum Srinivas (dims@yahoo.com) */ public class SunJSSESocketFactory extends JSSESocketFactory implements SecureSocketFactory { /** Field keystoreType */ private String keystoreType; /** Field defaultKeystoreType */ static String defaultKeystoreType = "JKS"; /** Field defaultProtocol */ static String defaultProtocol = "TLS"; /** Field defaultAlgorithm */ static String defaultAlgorithm = "SunX509"; /** Field defaultClientAuth */ static boolean defaultClientAuth = false; /** Field clientAuth */ private boolean clientAuth = false; /** Field defaultKeystoreFile */ static String defaultKeystoreFile = System.getProperty("user.home") + "/.keystore"; /** Field defaultKeyPass */ static String defaultKeyPass = "changeit"; /** * Constructor JSSESocketFactory * * @param attributes */ public SunJSSESocketFactory(Hashtable attributes) { super(attributes); } /** * Read the keystore, init the SSL socket factory * * @throws IOException */ protected void initFactory() throws IOException { try { Security.addProvider(new sun.security.provider.Sun()); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //Configuration specified in wsdd. SSLContext context = getContext(); sslFactory = context.getSocketFactory(); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e.getMessage()); } } /** * gets a SSL Context * * @return SSLContext * @throws Exception */ protected SSLContext getContext() throws Exception { if(attributes == null) { SSLContext context = com.sun.net.ssl.SSLContext.getInstance("SSL"); // SSL // init context with the key managers context.init(null, null, null); return context; } // Please don't change the name of the attribute - other // software may depend on it ( j2ee for sure ) String keystoreFile = (String) attributes.get("keystore"); if (keystoreFile == null) { keystoreFile = defaultKeystoreFile; } keystoreType = (String) attributes.get("keystoreType"); if (keystoreType == null) { keystoreType = defaultKeystoreType; } // determine whether we want client authentication // the presence of the attribute enables client auth clientAuth = null != (String) attributes.get("clientauth"); String keyPass = (String) attributes.get("keypass"); if (keyPass == null) { keyPass = defaultKeyPass; } String keystorePass = (String) attributes.get("keystorePass"); if (keystorePass == null) { keystorePass = keyPass; } // protocol for the SSL ie - TLS, SSL v3 etc. String protocol = (String) attributes.get("protocol"); if (protocol == null) { protocol = defaultProtocol; } // Algorithm used to encode the certificate ie - SunX509 String algorithm = (String) attributes.get("algorithm"); if (algorithm == null) { algorithm = defaultAlgorithm; } // You can't use ssl without a server certificate. // Create a KeyStore ( to get server certs ) KeyStore kstore = initKeyStore(keystoreFile, keystorePass); // Key manager will extract the server key com.sun.net.ssl.KeyManagerFactory kmf = com.sun.net.ssl.KeyManagerFactory.getInstance(algorithm); kmf.init(kstore, keyPass.toCharArray()); // If client authentication is needed, set up TrustManager com.sun.net.ssl.TrustManager[] tm = null; if (clientAuth) { com.sun.net.ssl.TrustManagerFactory tmf = com.sun.net.ssl.TrustManagerFactory.getInstance("SunX509"); tmf.init(kstore); tm = tmf.getTrustManagers(); } // Create a SSLContext ( to create the ssl factory ) // This is the only way to use server sockets with JSSE 1.0.1 SSLContext context = com.sun.net.ssl.SSLContext.getInstance(protocol); // SSL // init context with the key managers context.init(kmf.getKeyManagers(), tm, new java.security.SecureRandom()); return context; } /** * intializes a keystore. * * @param keystoreFile * @param keyPass * * @return keystore * @throws IOException */ private KeyStore initKeyStore(String keystoreFile, String keyPass) throws IOException { try { KeyStore kstore = KeyStore.getInstance(keystoreType); InputStream istream = new FileInputStream(keystoreFile); kstore.load(istream, keyPass.toCharArray()); return kstore; } catch (FileNotFoundException fnfe) { throw fnfe; } catch (IOException ioe) { throw ioe; } catch (Exception ex) { ex.printStackTrace(); throw new IOException("Exception trying to load keystore " + keystoreFile + ": " + ex.getMessage()); } } }
7,652
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/SunFakeTrustSocketFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import java.util.Hashtable; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import com.sun.net.ssl.SSLContext; import com.sun.net.ssl.TrustManager; import com.sun.net.ssl.X509TrustManager; /** * Hook for Axis sender, allowing unsigned server certs */ public class SunFakeTrustSocketFactory extends SunJSSESocketFactory { /** Field log */ protected static Log log = LogFactory.getLog(SunFakeTrustSocketFactory.class.getName()); /** * Constructor FakeTrustSocketFactory * * @param attributes */ public SunFakeTrustSocketFactory(Hashtable attributes) { super(attributes); } /** * Method getContext * * @return * * @throws Exception */ protected SSLContext getContext() throws Exception { try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, // we don't need no stinkin KeyManager new TrustManager[]{new FakeX509TrustManager()}, new java.security.SecureRandom()); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("ftsf00")); } return sc; } catch (Exception exc) { log.error(Messages.getMessage("ftsf01"), exc); throw new Exception(Messages.getMessage("ftsf02")); } } /** * Class FakeX509TrustManager */ public static class FakeX509TrustManager implements X509TrustManager { /** Field log */ protected static Log log = LogFactory.getLog(FakeX509TrustManager.class.getName()); /** * Method isClientTrusted * * @param chain * * @return */ public boolean isClientTrusted(java.security.cert .X509Certificate[] chain) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("ftsf03")); } return true; } /** * Method isServerTrusted * * @param chain * * @return */ public boolean isServerTrusted(java.security.cert .X509Certificate[] chain) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("ftsf04")); } return true; } /** * Method getAcceptedIssuers * * @return */ public java.security.cert.X509Certificate[] getAcceptedIssuers() { if (log.isDebugEnabled()) { log.debug(Messages.getMessage("ftsf05")); } return null; } } }
7,653
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/DefaultHTTPTransportClientProperties.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import org.apache.axis.AxisProperties; /** * @author Richard A. Sitze */ public class DefaultHTTPTransportClientProperties implements TransportClientProperties { private static final String emptyString = ""; protected String proxyHost = null; protected String nonProxyHosts = null; protected String proxyPort = null; protected String proxyUser = null; protected String proxyPassword = null; /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyHost() */ public String getProxyHost() { if (proxyHost == null) { proxyHost = AxisProperties.getProperty("http.proxyHost"); if (proxyHost == null) proxyHost = emptyString; } return proxyHost; } /** * @see org.apache.axis.components.net.TransportClientProperties#getNonProxyHosts() */ public String getNonProxyHosts() { if (nonProxyHosts == null) { nonProxyHosts = AxisProperties.getProperty("http.nonProxyHosts"); if (nonProxyHosts == null) nonProxyHosts = emptyString; } return nonProxyHosts; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyPort() */ public String getProxyPort() { if (proxyPort == null) { proxyPort = AxisProperties.getProperty("http.proxyPort"); if (proxyPort == null) proxyPort = emptyString; } return proxyPort; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyUser() */ public String getProxyUser() { if (proxyUser == null) { proxyUser = AxisProperties.getProperty("http.proxyUser"); if (proxyUser == null) proxyUser = emptyString; } return proxyUser; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyPassword() */ public String getProxyPassword() { if (proxyPassword == null) { proxyPassword = AxisProperties.getProperty("http.proxyPassword"); if (proxyPassword == null) proxyPassword = emptyString; } return proxyPassword; } }
7,654
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/SocketFactoryFactory.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.components.net; import org.apache.axis.AxisProperties; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.Hashtable; /** * Class SocketFactoryFactory * * @author * @version %I%, %G% */ public class SocketFactoryFactory { /** Field log */ protected static Log log = LogFactory.getLog(SocketFactoryFactory.class.getName()); /** socket factory */ private static Hashtable factories = new Hashtable(); private static final Class classes[] = new Class[] { Hashtable.class }; static { AxisProperties.setClassOverrideProperty(SocketFactory.class, "axis.socketFactory"); AxisProperties.setClassDefault(SocketFactory.class, "org.apache.axis.components.net.DefaultSocketFactory"); AxisProperties.setClassOverrideProperty(SecureSocketFactory.class, "axis.socketSecureFactory"); AxisProperties.setClassDefault(SecureSocketFactory.class, "org.apache.axis.components.net.JSSESocketFactory"); } /** * Returns a copy of the environment's default socket factory. * * @param protocol Today this only supports "http" &amp; "https". * @param attributes * * @return */ public static synchronized SocketFactory getFactory(String protocol, Hashtable attributes) { SocketFactory theFactory = (SocketFactory)factories.get(protocol); if (theFactory == null) { Object objects[] = new Object[] { attributes }; if (protocol.equalsIgnoreCase("http")) { theFactory = (SocketFactory) AxisProperties.newInstance(SocketFactory.class, classes, objects); } else if (protocol.equalsIgnoreCase("https")) { theFactory = (SecureSocketFactory) AxisProperties.newInstance(SecureSocketFactory.class, classes, objects); } if (theFactory != null) { factories.put(protocol, theFactory); } } return theFactory; } }
7,655
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/JSSESocketFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import javax.naming.InvalidNameException; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.apache.axis.utils.Messages; import org.apache.axis.utils.StringUtils; import org.apache.axis.utils.XMLUtils; /** * SSL socket factory. It _requires_ a valid RSA key and * JSSE. (borrowed code from tomcat) * * THIS CODE STILL HAS DEPENDENCIES ON sun.* and com.sun.* * * @author Davanum Srinivas (dims@yahoo.com) */ public class JSSESocketFactory extends DefaultSocketFactory implements SecureSocketFactory { // This is a a sorted list, if you insert new elements do it orderdered. private final static String[] BAD_COUNTRY_2LDS = {"ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org"}; /** Field sslFactory */ protected SSLSocketFactory sslFactory = null; /** * Constructor JSSESocketFactory * * @param attributes */ public JSSESocketFactory(Hashtable attributes) { super(attributes); } /** * Initialize the SSLSocketFactory * @throws IOException */ protected void initFactory() throws IOException { sslFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); } /** * creates a secure socket * * @param host * @param port * @param otherHeaders * @param useFullURL * * @return Socket * @throws Exception */ public Socket create( String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { if (sslFactory == null) { initFactory(); } if (port == -1) { port = 443; } TransportClientProperties tcp = TransportClientPropertiesFactory.create("https"); boolean hostInNonProxyList = isHostInNonProxyList(host, tcp.getNonProxyHosts()); Socket sslSocket = null; if (tcp.getProxyHost().length() == 0 || hostInNonProxyList) { // direct SSL connection sslSocket = sslFactory.createSocket(host, port); } else { // Default proxy port is 80, even for https int tunnelPort = (tcp.getProxyPort().length() != 0) ? Integer.parseInt(tcp.getProxyPort()) : 80; if (tunnelPort < 0) tunnelPort = 80; // Create the regular socket connection to the proxy Socket tunnel = new Socket(tcp.getProxyHost(), tunnelPort); // The tunnel handshake method (condensed and made reflexive) OutputStream tunnelOutputStream = tunnel.getOutputStream(); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(tunnelOutputStream))); // More secure version... engage later? // PasswordAuthentication pa = // Authenticator.requestPasswordAuthentication( // InetAddress.getByName(tunnelHost), // tunnelPort, "SOCK", "Proxy","HTTP"); // if(pa == null){ // printDebug("No Authenticator set."); // }else{ // printDebug("Using Authenticator."); // tunnelUser = pa.getUserName(); // tunnelPassword = new String(pa.getPassword()); // } out.print("CONNECT " + host + ":" + port + " HTTP/1.0\r\n" + "User-Agent: AxisClient"); if (tcp.getProxyUser().length() != 0 && tcp.getProxyPassword().length() != 0) { // add basic authentication header for the proxy String encodedPassword = XMLUtils.base64encode((tcp.getProxyUser() + ":" + tcp.getProxyPassword()).getBytes()); out.print("\nProxy-Authorization: Basic " + encodedPassword); } out.print("\nContent-Length: 0"); out.print("\nPragma: no-cache"); out.print("\r\n\r\n"); out.flush(); InputStream tunnelInputStream = tunnel.getInputStream(); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("isNull00", "tunnelInputStream", "" + (tunnelInputStream == null))); } String replyStr = ""; // Make sure to read all the response from the proxy to prevent SSL negotiation failure // Response message terminated by two sequential newlines int newlinesSeen = 0; boolean headerDone = false; /* Done on first newline */ while (newlinesSeen < 2) { int i = tunnelInputStream.read(); if (i < 0) { throw new IOException("Unexpected EOF from proxy"); } if (i == '\n') { headerDone = true; ++newlinesSeen; } else if (i != '\r') { newlinesSeen = 0; if (!headerDone) { replyStr += String.valueOf((char) i); } } } if (StringUtils.startsWithIgnoreWhitespaces("HTTP/1.0 200", replyStr) && StringUtils.startsWithIgnoreWhitespaces("HTTP/1.1 200", replyStr)) { throw new IOException(Messages.getMessage("cantTunnel00", new String[]{ tcp.getProxyHost(), "" + tunnelPort, replyStr})); } // End of condensed reflective tunnel handshake method sslSocket = sslFactory.createSocket(tunnel, host, port, true); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("setupTunnel00", tcp.getProxyHost(), "" + tunnelPort)); } } ((SSLSocket) sslSocket).startHandshake(); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("createdSSL00")); } verifyHostName(host, (SSLSocket) sslSocket); return sslSocket; } /** * Verifies that the given hostname in certicifate is the hostname we are trying to connect to. * This resolves CVE-2012-5784 and CVE-2014-3596 * @param host * @param ssl * @throws IOException */ private static void verifyHostName(String host, SSLSocket ssl) throws IOException { if (host == null) { throw new IllegalArgumentException("host to verify was null"); } SSLSession session = ssl.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server's chain. // Hopefully this will unearth the real problem: InputStream in = ssl.getInputStream(); in.available(); /* If you're looking at the 2 lines of code above because you're running into a problem, you probably have two options: #1. Clean up the certificate chain that your server is presenting (e.g. edit "/etc/apache2/server.crt" or wherever it is your server's certificate chain is defined). OR #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an exception, // maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } Certificate[] certs = session.getPeerCertificates(); verifyHostName(host.trim().toLowerCase(Locale.US), (X509Certificate) certs[0]); } /** * Extract the names from the certificate and tests host matches one of them * @param host * @param cert * @throws SSLException */ private static void verifyHostName(final String host, X509Certificate cert) throws SSLException { // I'm okay with being case-insensitive when comparing the host we used // to establish the socket to the hostname in the certificate. // Don't trim the CN, though. String[] cns = getCNs(cert); String[] subjectAlts = getDNSSubjectAlts(cert); verifyHostName(host, cns, subjectAlts); } /** * Extract all alternative names from a certificate. * @param cert * @return */ private static String[] getDNSSubjectAlts(X509Certificate cert) { LinkedList subjectAltList = new LinkedList(); Collection c = null; try { c = cert.getSubjectAlternativeNames(); } catch (CertificateParsingException cpe) { // Should probably log.debug() this? cpe.printStackTrace(); } if (c != null) { Iterator it = c.iterator(); while (it.hasNext()) { List list = (List) it.next(); int type = ((Integer) list.get(0)).intValue(); // If type is 2, then we've got a dNSName if (type == 2) { String s = (String) list.get(1); subjectAltList.add(s); } } } if (!subjectAltList.isEmpty()) { String[] subjectAlts = new String[subjectAltList.size()]; subjectAltList.toArray(subjectAlts); return subjectAlts; } else { return new String[0]; } } /** * Verifies * @param host * @param cn * @param subjectAlts * @throws SSLException */ private static void verifyHostName(final String host, String[] cns, String[] subjectAlts)throws SSLException{ StringBuffer cnTested = new StringBuffer(); for (int i = 0; i < subjectAlts.length; i++){ String name = subjectAlts[i]; if (name != null) { name = name.toLowerCase(Locale.US); if (verifyHostName(host, name)){ return; } cnTested.append("/").append(name); } } for (int i = 0; i < cns.length; i++) { String cn = cns[i]; if (cn != null) { cn = cn.toLowerCase(Locale.US); if (verifyHostName(host, cn)) { return; } cnTested.append("/").append(cn); } } throw new SSLException("hostname in certificate didn't match: <" + host + "> != <" + cnTested + ">"); } private static boolean verifyHostName(final String host, final String cn){ if (doWildCard(cn) && !isIPAddress(host)) { return matchesWildCard(cn, host); } return host.equalsIgnoreCase(cn); } private static boolean doWildCard(String cn) { // Contains a wildcard // wildcard in the first block // not an ipaddress (ip addres must explicitily be equal) // not using 2nd level common tld : ex: not for *.co.uk String parts[] = cn.split("\\."); return parts.length >= 3 && parts[0].endsWith("*") && acceptableCountryWildcard(cn) && !isIPAddress(cn); } private static final Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); private static final Pattern IPV6_STD_PATTERN = Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); private static boolean isIPAddress(final String hostname) { return hostname != null && ( IPV4_PATTERN.matcher(hostname).matches() || IPV6_STD_PATTERN.matcher(hostname).matches() || IPV6_HEX_COMPRESSED_PATTERN.matcher(hostname).matches() ); } private static boolean acceptableCountryWildcard(final String cn) { // The CN better have at least two dots if it wants wildcard action, // but can't be [*.co.uk] or [*.co.jp] or [*.org.uk], etc... // The [*.co.uk] problem is an interesting one. Should we just // hope that CA's would never foolishly allow such a // certificate to happen? String[] parts = cn.split("\\."); // Only checks for 3 levels, with country code of 2 letters. if (parts.length > 3 || parts[parts.length - 1].length() != 2) { return true; } String countryCode = parts[parts.length - 2]; return Arrays.binarySearch(BAD_COUNTRY_2LDS, countryCode) < 0; } private static boolean matchesWildCard(final String cn, final String hostName) { String parts[] = cn.split("\\."); boolean match = false; String firstpart = parts[0]; if (firstpart.length() > 1) { // server∗ // e.g. server String prefix = firstpart.substring(0, firstpart.length() - 1); // skipwildcard part from cn String suffix = cn.substring(firstpart.length()); // skip wildcard part from host String hostSuffix = hostName.substring(prefix.length()); match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix); } else { match = hostName.endsWith(cn.substring(1)); } if (match) { // I f we ’ r e i n s t r i c t mode , // [ ∗.foo.com] is not allowed to match [a.b.foo.com] match = countDots(hostName) == countDots(cn); } return match; } private static int countDots(final String data) { int dots = 0; for (int i = 0; i < data.length(); i++) { if (data.charAt(i) == '.') { dots += 1; } } return dots; } private static String[] getCNs(X509Certificate cert) { // Note: toString() seems to do a better job than getName() // // For example, getName() gives me this: // 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d // // whereas toString() gives me this: // EMAILADDRESS=juliusdavies@cucbc.com String subjectPrincipal = cert.getSubjectX500Principal().toString(); return getCNs(subjectPrincipal); } private static String[] getCNs(String subjectPrincipal) { if (subjectPrincipal == null) { return null; } final List cns = new ArrayList(); try { final LdapName subjectDN = new LdapName(subjectPrincipal); final List rdns = subjectDN.getRdns(); for (int i = rdns.size() - 1; i >= 0; i--) { final Rdn rds = (Rdn) rdns.get(i); final Attributes attributes = rds.toAttributes(); final Attribute cn = attributes.get("cn"); if (cn != null) { try { final Object value = cn.get(); if (value != null) { cns.add(value.toString()); } } catch (NamingException ignore) {} } } } catch (InvalidNameException ignore) { } return cns.isEmpty() ? null : (String[]) cns.toArray(new String[ cns.size() ]); } }
7,656
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/TransportClientPropertiesFactory.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.components.net; import org.apache.axis.AxisProperties; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; import java.util.HashMap; /** * @author Richard A. Sitze */ public class TransportClientPropertiesFactory { protected static Log log = LogFactory.getLog(SocketFactoryFactory.class.getName()); private static HashMap cache = new HashMap(); private static HashMap defaults = new HashMap(); static { defaults.put("http", DefaultHTTPTransportClientProperties.class); defaults.put("https", DefaultHTTPSTransportClientProperties.class); } public static TransportClientProperties create(String protocol) { TransportClientProperties tcp = (TransportClientProperties)cache.get(protocol); if (tcp == null) { tcp = (TransportClientProperties) AxisProperties.newInstance(TransportClientProperties.class, (Class)defaults.get(protocol)); if (tcp != null) { cache.put(protocol, tcp); } } return tcp; } }
7,657
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/DefaultSocketFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.Base64; import org.apache.axis.transport.http.HTTPConstants; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import java.net.Socket; import java.util.Hashtable; import java.util.StringTokenizer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Default socket factory. * * @author Davanum Srinivas (dims@yahoo.com) */ public class DefaultSocketFactory implements SocketFactory { /** Field log */ protected static Log log = LogFactory.getLog(DefaultSocketFactory.class.getName()); /** Field CONNECT_TIMEOUT */ public static String CONNECT_TIMEOUT = "axis.client.connect.timeout"; /** attributes */ protected Hashtable attributes = null; private static boolean plain; private static Class inetClass; private static Constructor inetConstructor; private static Constructor socketConstructor; private static Method connect; static { try { inetClass = Class.forName("java.net.InetSocketAddress"); plain = false; inetConstructor = inetClass.getConstructor(new Class[]{String.class, int.class}); socketConstructor = Socket.class.getConstructor(new Class[]{}); connect = Socket.class.getMethod("connect", new Class[]{inetClass.getSuperclass(), int.class}); } catch (Exception e) { plain = true; } } /** * Constructor is used only by subclasses. * * @param attributes */ public DefaultSocketFactory(Hashtable attributes) { this.attributes = attributes; } /** * Creates a socket. * * @param host * @param port * @param otherHeaders * @param useFullURL * * @return Socket * * @throws Exception */ public Socket create( String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { int timeout = 0; if (attributes != null) { String value = (String)attributes.get(CONNECT_TIMEOUT); timeout = (value != null) ? Integer.parseInt(value) : 0; } TransportClientProperties tcp = TransportClientPropertiesFactory.create("http"); Socket sock = null; boolean hostInNonProxyList = isHostInNonProxyList(host, tcp.getNonProxyHosts()); if (tcp.getProxyUser().length() != 0) { StringBuffer tmpBuf = new StringBuffer(); tmpBuf.append(tcp.getProxyUser()) .append(":") .append(tcp.getProxyPassword()); otherHeaders.append(HTTPConstants.HEADER_PROXY_AUTHORIZATION) .append(": Basic ") .append(Base64.encode(tmpBuf.toString().getBytes())) .append("\r\n"); } if (port == -1) { port = 80; } if ((tcp.getProxyHost().length() == 0) || (tcp.getProxyPort().length() == 0) || hostInNonProxyList) { sock = create(host, port, timeout); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("createdHTTP00")); } } else { sock = create(tcp.getProxyHost(), new Integer(tcp.getProxyPort()).intValue(), timeout); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("createdHTTP01", tcp.getProxyHost(), tcp.getProxyPort())); } useFullURL.value = true; } return sock; } /** * Creates a socket with connect timeout using reflection API * * @param host * @param port * @param timeout * @return * @throws Exception */ private static Socket create(String host, int port, int timeout) throws Exception { Socket sock = null; if (plain || timeout == 0) { sock = new Socket(host, port); } else { Object address = inetConstructor.newInstance(new Object[]{host, new Integer(port)}); sock = (Socket)socketConstructor.newInstance(new Object[]{}); connect.invoke(sock, new Object[]{address, new Integer(timeout)}); } return sock; } /** * Check if the specified host is in the list of non proxy hosts. * * @param host host name * @param nonProxyHosts string containing the list of non proxy hosts * * @return true/false */ protected boolean isHostInNonProxyList(String host, String nonProxyHosts) { if ((nonProxyHosts == null) || (host == null)) { return false; } /* * The http.nonProxyHosts system property is a list enclosed in * double quotes with items separated by a vertical bar. */ StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|\""); while (tokenizer.hasMoreTokens()) { String pattern = tokenizer.nextToken(); if (log.isDebugEnabled()) { log.debug(Messages.getMessage("match00", new String[]{"HTTPSender", host, pattern})); } if (match(pattern, host, false)) { return true; } } return false; } /** * Matches a string against a pattern. The pattern contains two special * characters: * '*' which means zero or more characters, * * @param pattern the (non-null) pattern to match against * @param str the (non-null) string that must be matched against the * pattern * @param isCaseSensitive * * @return <code>true</code> when the string matches against the pattern, * <code>false</code> otherwise. */ protected static boolean match(String pattern, String str, boolean isCaseSensitive) { char[] patArr = pattern.toCharArray(); char[] strArr = str.toCharArray(); int patIdxStart = 0; int patIdxEnd = patArr.length - 1; int strIdxStart = 0; int strIdxEnd = strArr.length - 1; char ch; boolean containsStar = false; for (int i = 0; i < patArr.length; i++) { if (patArr[i] == '*') { containsStar = true; break; } } if (!containsStar) { // No '*'s, so we make a shortcut if (patIdxEnd != strIdxEnd) { return false; // Pattern and string do not have the same size } for (int i = 0; i <= patIdxEnd; i++) { ch = patArr[i]; if (isCaseSensitive && (ch != strArr[i])) { return false; // Character mismatch } if (!isCaseSensitive && (Character.toUpperCase(ch) != Character.toUpperCase(strArr[i]))) { return false; // Character mismatch } } return true; // String matches against pattern } if (patIdxEnd == 0) { return true; // Pattern contains only '*', which matches anything } // Process characters before first star while ((ch = patArr[patIdxStart]) != '*' && (strIdxStart <= strIdxEnd)) { if (isCaseSensitive && (ch != strArr[strIdxStart])) { return false; // Character mismatch } if (!isCaseSensitive && (Character.toUpperCase(ch) != Character.toUpperCase(strArr[strIdxStart]))) { return false; // Character mismatch } patIdxStart++; strIdxStart++; } if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. for (int i = patIdxStart; i <= patIdxEnd; i++) { if (patArr[i] != '*') { return false; } } return true; } // Process characters after last star while ((ch = patArr[patIdxEnd]) != '*' && (strIdxStart <= strIdxEnd)) { if (isCaseSensitive && (ch != strArr[strIdxEnd])) { return false; // Character mismatch } if (!isCaseSensitive && (Character.toUpperCase(ch) != Character.toUpperCase(strArr[strIdxEnd]))) { return false; // Character mismatch } patIdxEnd--; strIdxEnd--; } if (strIdxStart > strIdxEnd) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. for (int i = patIdxStart; i <= patIdxEnd; i++) { if (patArr[i] != '*') { return false; } } return true; } // process pattern between stars. padIdxStart and patIdxEnd point // always to a '*'. while ((patIdxStart != patIdxEnd) && (strIdxStart <= strIdxEnd)) { int patIdxTmp = -1; for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { if (patArr[i] == '*') { patIdxTmp = i; break; } } if (patIdxTmp == patIdxStart + 1) { // Two stars next to each other, skip the first one. patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = (patIdxTmp - patIdxStart - 1); int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { ch = patArr[patIdxStart + j + 1]; if (isCaseSensitive && (ch != strArr[strIdxStart + i + j])) { continue strLoop; } if (!isCaseSensitive && (Character .toUpperCase(ch) != Character .toUpperCase(strArr[strIdxStart + i + j]))) { continue strLoop; } } foundIdx = strIdxStart + i; break; } if (foundIdx == -1) { return false; } patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } // All characters in the string are used. Check if only '*'s are left // in the pattern. If so, we succeeded. Otherwise failure. for (int i = patIdxStart; i <= patIdxEnd; i++) { if (patArr[i] != '*') { return false; } } return true; } }
7,658
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/TransportClientProperties.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; /** * @author Richard A. Sitze */ public interface TransportClientProperties { /** * Returns a valid String, may be empty (""). */ public String getProxyHost(); /** * Returns a valid String, may be empty (""). */ public String getNonProxyHosts(); /** * Returns a valid String, may be empty (""). */ public String getProxyPort(); /** * Returns a valid String, may be empty (""). */ public String getProxyUser(); /** * Returns a valid String, may be empty (""). */ public String getProxyPassword(); }
7,659
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/DefaultHTTPSTransportClientProperties.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.net; import org.apache.axis.AxisProperties; /** * @author Richard A. Sitze */ public class DefaultHTTPSTransportClientProperties extends DefaultHTTPTransportClientProperties { /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyHost() */ public String getProxyHost() { if (proxyHost == null) { proxyHost = AxisProperties.getProperty("https.proxyHost"); super.getProxyHost(); } return proxyHost; } /** * @see org.apache.axis.components.net.TransportClientProperties#getNonProxyHosts() */ public String getNonProxyHosts() { if (nonProxyHosts == null) { nonProxyHosts = AxisProperties.getProperty("https.nonProxyHosts"); super.getNonProxyHosts(); } return nonProxyHosts; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyPort() */ public String getProxyPort() { if (proxyPort == null) { proxyPort = AxisProperties.getProperty("https.proxyPort"); super.getProxyPort(); } return proxyPort; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyUser() */ public String getProxyUser() { if (proxyUser == null) { proxyUser = AxisProperties.getProperty("https.proxyUser"); super.getProxyUser(); } return proxyUser; } /** * @see org.apache.axis.components.net.TransportClientProperties#getProxyPassword() */ public String getProxyPassword() { if (proxyPassword == null) { proxyPassword = AxisProperties.getProperty("https.proxyPassword"); super.getProxyPassword(); } return proxyPassword; } }
7,660
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/net/SecureSocketFactory.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.components.net; /** * Secure Socket factory. * This has a separate interface to allow discovery (by interface) * and runtime distinction to be made between Socket &amp; SecureSockets. * * @author Richard A. Sitze * @author Davanum Srinivas (dims@yahoo.com) */ public interface SecureSocketFactory extends SocketFactory { }
7,661
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/logger/LogFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.logger; import org.apache.commons.discovery.tools.DiscoverSingleton; import org.apache.commons.logging.Log; import java.security.AccessController; import java.security.PrivilegedAction; /** * @author Richard A. Sitze */ public class LogFactory { /** * Override group context.. */ private static final org.apache.commons.logging.LogFactory logFactory = getLogFactory(); public static Log getLog(String name) { return org.apache.commons.logging.LogFactory.getLog(name); } private static final org.apache.commons.logging.LogFactory getLogFactory() { return (org.apache.commons.logging.LogFactory) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return DiscoverSingleton.find(org.apache.commons.logging.LogFactory.class, org.apache.commons.logging.LogFactory.FACTORY_PROPERTIES, org.apache.commons.logging.LogFactory.FACTORY_DEFAULT); } }); } }
7,662
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/XMLEncoderFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.commons.discovery.ResourceNameIterator; import org.apache.commons.discovery.resource.ClassLoaders; import org.apache.commons.discovery.resource.names.DiscoverServiceNames; import org.apache.commons.logging.Log; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; /** * Factory for XMLEncoder * * @author <a href="mailto:jens@void.fm">Jens Schumann</a> * @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a> */ public class XMLEncoderFactory { protected static Log log = LogFactory.getLog(XMLEncoderFactory.class.getName()); public static final String ENCODING_UTF_8 = "UTF-8"; public static final String ENCODING_UTF_16 = "UTF-16"; public static final String DEFAULT_ENCODING = ENCODING_UTF_8; private static Map encoderMap = new HashMap(); private static final String PLUGABLE_PROVIDER_FILENAME = "org.apache.axis.components.encoding.XMLEncoder"; static { encoderMap.put(ENCODING_UTF_8, new UTF8Encoder()); encoderMap.put(ENCODING_UTF_16, new UTF16Encoder()); encoderMap.put(ENCODING_UTF_8.toLowerCase(), new UTF8Encoder()); encoderMap.put(ENCODING_UTF_16.toLowerCase(), new UTF16Encoder()); try { loadPluggableEncoders(); } catch (Throwable t){ String msg=t + JavaUtils.LS + JavaUtils.stackToString(t); log.info(Messages.getMessage("exception01",msg)); } } /** * Returns the default encoder * @return */ public static XMLEncoder getDefaultEncoder() { try { return getEncoder(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // as far I know J++ VMs will throw this exception throw new IllegalStateException(Messages.getMessage("unsupportedDefaultEncoding00", DEFAULT_ENCODING)); } } /** * Returns the requested encoder * @param encoding * @return * @throws UnsupportedEncodingException */ public static XMLEncoder getEncoder(String encoding) throws UnsupportedEncodingException { XMLEncoder encoder = (XMLEncoder) encoderMap.get(encoding); if (encoder == null) { encoder = new DefaultXMLEncoder(encoding); encoderMap.put(encoding, encoder); } return encoder; } /** Look for file META-INF/services/org.apache.axis.components.encoding.XMLEncoder in all the JARS, get the classes listed in those files and add them to encoders list if they are valid encoders. Here is how the scheme would work. A company providing a new encoder will jar up their encoder related classes in a JAR file. The following file containing the name of the new encoder class is also made part of this JAR file. META-INF/services/org.apache.axis.components.encoding.XMLEncoder By making this JAR part of the webapp, the new encoder will be automatically discovered. */ private static void loadPluggableEncoders() { ClassLoader clzLoader = XMLEncoder.class.getClassLoader(); ClassLoaders loaders = new ClassLoaders(); loaders.put(clzLoader); DiscoverServiceNames dsn = new DiscoverServiceNames(loaders); ResourceNameIterator iter = dsn.findResourceNames(PLUGABLE_PROVIDER_FILENAME); while (iter.hasNext()) { String className = iter.nextResourceName(); try { Object o = Class.forName(className).newInstance(); if (o instanceof XMLEncoder) { XMLEncoder encoder = (XMLEncoder) o; encoderMap.put(encoder.getEncoding(), encoder); encoderMap.put(encoder.getEncoding().toLowerCase(), encoder); } } catch (Exception e) { String msg = e + JavaUtils.LS + JavaUtils.stackToString(e); log.info(Messages.getMessage("exception01", msg)); continue; } } } }
7,663
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/UTF8Encoder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import org.apache.axis.i18n.Messages; import java.io.IOException; import java.io.Writer; /** * UTF-8 Encoder. * * @author <a href="mailto:jens@void.fm">Jens Schumann</a> * @see <a href="http://encoding.org">encoding.org</a> * @see <a href="http://czyborra.com/utf/#UTF-8">UTF 8 explained</a> */ class UTF8Encoder extends AbstractXMLEncoder { /** * gets the encoding supported by this encoder * * @return string */ public String getEncoding() { return XMLEncoderFactory.ENCODING_UTF_8; } /** * write the encoded version of a given string * * @param writer writer to write this string to * @param xmlString string to be encoded */ public void writeEncoded(Writer writer, String xmlString) throws IOException { if (xmlString == null) { return; } int length = xmlString.length(); char character; for (int i = 0; i < length; i++) { character = xmlString.charAt( i ); switch (character) { // we don't care about single quotes since axis will // use double quotes anyway case '&': writer.write(AMP); break; case '"': writer.write(QUOTE); break; case '<': writer.write(LESS); break; case '>': writer.write(GREATER); break; case '\n': writer.write(LF); break; case '\r': writer.write(CR); break; case '\t': writer.write(TAB); break; default: if (character < 0x20) { throw new IllegalArgumentException(Messages.getMessage( "invalidXmlCharacter00", Integer.toHexString(character), xmlString.substring(0, i))); } else if (character > 0x7F) { writer.write("&#x"); writer.write(Integer.toHexString(character).toUpperCase()); writer.write(";"); } else { writer.write(character); } break; } } } }
7,664
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/DefaultXMLEncoder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; public class DefaultXMLEncoder extends UTF8Encoder { private String encoding = null; public DefaultXMLEncoder(String encoding) { this.encoding = encoding; } /** * gets the encoding supported by this encoder * * @return string */ public String getEncoding() { return encoding; } }
7,665
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/XMLEncoder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import java.io.Writer; import java.io.IOException; /** * Interface for XMLEncoders */ public interface XMLEncoder { /** * gets the encoding supported by this encoder * @return string */ public String getEncoding(); /** * encode a given string * @param xmlString string to be encoded * @return encoded string */ public String encode(String xmlString); /** * write the encoded version of a given string * @param writer writer to write this string to * @param xmlString string to be encoded */ public void writeEncoded(Writer writer, String xmlString) throws IOException; }
7,666
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/EncodedByteArray.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import java.io.UnsupportedEncodingException; /** * * Simple byte array with variable array length, used within the * XMLEncoder. * * It is used as a ByteArrayOutputStream replacement to limit * the size of created temporary objects * * * @author <a href="mailto:jens@void.fm">Jens Schumann</a> */ class EncodedByteArray { private byte[] array = null; private int pointer; private final double PADDING = 1.5; public EncodedByteArray(byte[] bytes, int startPos, int length) { // string length will be at least the size of the byte array array = new byte[(int) (bytes.length * PADDING)]; System.arraycopy(bytes, startPos, array, 0, length); pointer = length; } public EncodedByteArray(int size) { array = new byte[size]; } public void append(int aByte) { if (pointer + 1 >= array.length) { byte[] newArray = new byte[(int) (array.length * PADDING)]; System.arraycopy(array, 0, newArray, 0, pointer); array = newArray; } array[pointer] = (byte) aByte; pointer++; } public void append(byte[] byteArray) { if (pointer + byteArray.length >= array.length) { byte[] newArray = new byte[((int)(array.length * PADDING)) + byteArray.length]; System.arraycopy(array, 0, newArray, 0, pointer); array = newArray; } System.arraycopy(byteArray, 0, array, pointer, byteArray.length); pointer += byteArray.length; } public void append(byte[] byteArray, int pos, int length) { if (pointer + length >= array.length) { byte[] newArray = new byte[((int) (array.length * PADDING)) + byteArray.length]; System.arraycopy(array, 0, newArray, 0, pointer); array = newArray; } System.arraycopy(byteArray, pos, array, pointer, length); pointer += length; } /** * convert to a string using the platform's default charset * @return string */ public String toString() { return new String(array, 0, pointer); } /** * convert the encoded byte array to a string according to the given charset * @param charsetName * @return string * @throws UnsupportedEncodingException */ public String toString(String charsetName) throws UnsupportedEncodingException { return new String(array, 0, pointer, charsetName); } }
7,667
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/AbstractXMLEncoder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import org.apache.axis.utils.Messages; /** * * Abstract class for XML String encoders. * * The new encoding mechanism fixes the following bugs/issues: * http://nagoya.apache.org/bugzilla/show_bug.cgi?id=15133 * http://nagoya.apache.org/bugzilla/show_bug.cgi?id=15494 * http://nagoya.apache.org/bugzilla/show_bug.cgi?id=19327 * * @author <a href="mailto:jens@void.fm">Jens Schumann</a> * @author <a href="mailto:dims@yahoo.com">Davanum Srinivas</a> * */ public abstract class AbstractXMLEncoder implements XMLEncoder { protected static final String AMP = "&amp;"; protected static final String QUOTE = "&quot;"; protected static final String LESS = "&lt;"; protected static final String GREATER = "&gt;"; protected static final String LF = "\n"; protected static final String CR = "\r"; protected static final String TAB = "\t"; /** * gets the encoding supported by this encoder * @return string */ public abstract String getEncoding(); /** * Encode a string * @param xmlString string to be encoded * @return encoded string */ public String encode(String xmlString) { if(xmlString == null) { return ""; } char[] characters = xmlString.toCharArray(); StringBuffer out = null; char character; for (int i = 0; i < characters.length; i++) { character = characters[i]; switch (character) { // we don't care about single quotes since axis will // use double quotes anyway case '&': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(AMP); break; case '"': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(QUOTE); break; case '<': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(LESS); break; case '>': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(GREATER); break; case '\n': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(LF); break; case '\r': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(CR); break; case '\t': if (out == null) { out = getInitialByteArray(xmlString, i); } out.append(TAB); break; default: if (character < 0x20) { throw new IllegalArgumentException(Messages.getMessage("invalidXmlCharacter00", Integer.toHexString(character), xmlString.substring(0, i))); } else { if (out != null) { out.append(character); } } break; } } if (out == null) { return xmlString; } return out.toString(); } protected StringBuffer getInitialByteArray(String aXmlString, int pos) { return new StringBuffer(aXmlString.substring(0, pos)); } }
7,668
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/encoding/UTF16Encoder.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.encoding; import org.apache.axis.i18n.Messages; import java.io.IOException; import java.io.Writer; /** * UTF-16 Encoder. * * @author <a href="mailto:jens@void.fm">Jens Schumann</a> * @see <a href="http://encoding.org">encoding.org</a> * @see <a href="http://czyborra.com/utf/#UTF-16">UTF 16 explained</a> */ class UTF16Encoder extends AbstractXMLEncoder { /** * gets the encoding supported by this encoder * @return string */ public String getEncoding() { return XMLEncoderFactory.ENCODING_UTF_16; } /** * write the encoded version of a given string * * @param writer writer to write this string to * @param xmlString string to be encoded */ public void writeEncoded(Writer writer, String xmlString) throws IOException { if (xmlString == null) { return; } int length = xmlString.length(); char character; for (int i = 0; i < length; i++) { character = xmlString.charAt( i ); switch (character) { // we don't care about single quotes since axis will // use double quotes anyway case '&': writer.write(AMP); break; case '"': writer.write(QUOTE); break; case '<': writer.write(LESS); break; case '>': writer.write(GREATER); break; case '\n': writer.write(LF); break; case '\r': writer.write(CR); break; case '\t': writer.write(TAB); break; default: if (character < 0x20) { throw new IllegalArgumentException(Messages.getMessage( "invalidXmlCharacter00", Integer.toHexString(character), xmlString.substring(0, i))); } else if (character > 0xFFFF) { writer.write((0xD7C0 + (character >> 10))); writer.write((0xDC00 | character & 0x3FF)); } else { writer.write(character); } break; } } } }
7,669
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/uuid/UUIDGenFactory.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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. */ /** * * UUIDGen adopted from the juddi project * (http://sourceforge.net/projects/juddi/) * */ package org.apache.axis.components.uuid; import org.apache.axis.AxisProperties; import org.apache.axis.components.logger.LogFactory; import org.apache.commons.logging.Log; /** * A Universally Unique Identifier (UUID) is a 128 bit number generated * according to an algorithm that is garanteed to be unique in time and space * from all other UUIDs. It consists of an IEEE 802 Internet Address and * various time stamps to ensure uniqueness. For a complete specification, * see ftp://ietf.org/internet-drafts/draft-leach-uuids-guids-01.txt [leach]. * * @author Steve Viens * @version 1.0 11/7/2000 * @since JDK1.2.2 */ public abstract class UUIDGenFactory { protected static Log log = LogFactory.getLog(UUIDGenFactory.class.getName()); static { AxisProperties.setClassOverrideProperty(UUIDGen.class, "axis.UUIDGenerator"); AxisProperties.setClassDefault(UUIDGen.class, "org.apache.axis.components.uuid.FastUUIDGen"); } /** * Returns an instance of UUIDGen */ public static UUIDGen getUUIDGen() { UUIDGen uuidgen = (UUIDGen) AxisProperties.newInstance(UUIDGen.class); log.debug("axis.UUIDGenerator:" + uuidgen.getClass().getName()); return uuidgen; } }
7,670
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/uuid/FastUUIDGen.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.components.uuid; import java.util.Random; import java.security.SecureRandom; /** * Creates time-based UUID's. See the <a href="http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt">UUID Internet Draft</a> for details. * * @author Jarek Gawor (gawor@apache.org) */ public class FastUUIDGen implements UUIDGen { private static Random secureRandom; private static String nodeStr; private static int clockSequence; private long lastTime = 0; static { // problem: the node should be the IEEE 802 ethernet address, but can not // be retrieved in Java yet. // see bug ID 4173528 // workaround (also suggested in bug ID 4173528) // If a system wants to generate UUIDs but has no IEE 802 compliant // network card or other source of IEEE 802 addresses, then this section // describes how to generate one. // The ideal solution is to obtain a 47 bit cryptographic quality random // number, and use it as the low 47 bits of the node ID, with the most // significant bit of the first octet of the node ID set to 1. This bit // is the unicast/multicast bit, which will never be set in IEEE 802 // addresses obtained from network cards; hence, there can never be a // conflict between UUIDs generated by machines with and without network // cards. try { secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN"); } catch (Exception e) { secureRandom = new Random(); } nodeStr = getNodeHexValue(); clockSequence = getClockSequence(); } private static String getNodeHexValue() { long node = 0; long nodeValue = 0; while ( (node = getBitsValue(nodeValue, 47, 47)) == 0 ) { nodeValue = secureRandom.nextLong(); } node = node | 0x800000000000L; return leftZeroPadString(Long.toHexString(node), 12); } private static int getClockSequence() { return secureRandom.nextInt(16384); } public String nextUUID() { long time = System.currentTimeMillis(); long timestamp = time * 10000; timestamp += 0x01b21dd2L << 32; timestamp += 0x13814000; synchronized(this) { if (time - lastTime <= 0) { clockSequence = ((clockSequence + 1) & 16383); } lastTime = time; } long timeLow = getBitsValue(timestamp, 32, 32); long timeMid = getBitsValue(timestamp, 48, 16); long timeHi = getBitsValue(timestamp, 64, 16) | 0x1000; long clockSeqLow = getBitsValue(clockSequence, 8, 8); long clockSeqHi = getBitsValue(clockSequence, 16, 8) | 0x80; String timeLowStr = leftZeroPadString(Long.toHexString(timeLow), 8); String timeMidStr = leftZeroPadString(Long.toHexString(timeMid), 4); String timeHiStr = leftZeroPadString(Long.toHexString(timeHi), 4); String clockSeqHiStr = leftZeroPadString(Long.toHexString(clockSeqHi), 2); String clockSeqLowStr = leftZeroPadString(Long.toHexString(clockSeqLow), 2); StringBuffer result = new StringBuffer(36); result.append(timeLowStr).append("-"); result.append(timeMidStr).append("-"); result.append(timeHiStr).append("-"); result.append(clockSeqHiStr).append(clockSeqLowStr); result.append("-").append(nodeStr); return result.toString(); } private static long getBitsValue(long value, int startBit, int bitLen) { return ((value << (64-startBit)) >>> (64-bitLen)); } private static final String leftZeroPadString(String bitString, int len) { if (bitString.length() < len) { int nbExtraZeros = len - bitString.length(); StringBuffer extraZeros = new StringBuffer(); for (int i = 0; i < nbExtraZeros; i++) { extraZeros.append("0"); } extraZeros.append(bitString); bitString = extraZeros.toString(); } return bitString; } }
7,671
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/uuid/UUIDGen.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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. */ /** * * UUIDGen adopted from the juddi project * (http://sourceforge.net/projects/juddi/) * */ package org.apache.axis.components.uuid; /** * A Universally Unique Identifier (UUID) is a 128 bit number generated * according to an algorithm that is garanteed to be unique in time and space * from all other UUIDs. It consists of an IEEE 802 Internet Address and * various time stamps to ensure uniqueness. For a complete specification, * see ftp://ietf.org/internet-drafts/draft-leach-uuids-guids-01.txt [leach]. * * @author Steve Viens * @version 1.0 11/7/2000 * @since JDK1.2.2 */ public interface UUIDGen { public String nextUUID(); }
7,672
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/components/uuid/SimpleUUIDGen.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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. */ /** * * UUIDGen adopted from the juddi project * (http://sourceforge.net/projects/juddi/) * */ package org.apache.axis.components.uuid; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; /** * Used to create new universally unique identifiers or UUID's (sometimes called * GUID's). UDDI UUID's are allways formmated according to DCE UUID conventions. * * @author Maarten Coene * @author Steve Viens * @version 0.3.2 3/25/2001 * @since JDK1.2.2 */ public class SimpleUUIDGen implements UUIDGen { private static final BigInteger countStart = new BigInteger("-12219292800000"); // 15 October 1582 private static final int clock_sequence = (new Random()).nextInt(16384); private static final byte ZERO = (byte) 48; // "0" private static final byte ONE = (byte) 49; // "1" private static Random secureRandom = null; static { // problem: the node should be the IEEE 802 ethernet address, but can not // be retrieved in Java yet. // see bug ID 4173528 // workaround (also suggested in bug ID 4173528) // If a system wants to generate UUIDs but has no IEE 802 compliant // network card or other source of IEEE 802 addresses, then this section // describes how to generate one. // The ideal solution is to obtain a 47 bit cryptographic quality random // number, and use it as the low 47 bits of the node ID, with the most // significant bit of the first octet of the node ID set to 1. This bit // is the unicast/multicast bit, which will never be set in IEEE 802 // addresses obtained from network cards; hence, there can never be a // conflict between UUIDs generated by machines with and without network // cards. try { secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN"); } catch (Exception e) { secureRandom = new Random(); } } /** * utility method which returns a bitString with left zero padding * for as many places as necessary to reach <tt>len</tt>; otherwise * returns bitString unaltered. * * @return a left zero padded string of at least <tt>len</tt> chars * @param bitString a String to pad * @param len the length under which bitString needs padding */ private static final String leftZeroPadString(String bitString, int len) { if (bitString.length() < len) { int nbExtraZeros = len - bitString.length(); StringBuffer extraZeros = new StringBuffer(); for (int i = 0; i < nbExtraZeros; i++) { extraZeros.append("0"); } extraZeros.append(bitString); bitString = extraZeros.toString(); } return bitString; } /** * Creates a new UUID. The algorithm used is described by The Open Group. * See <a href="http://www.opengroup.org/onlinepubs/009629399/apdxa.htm"> * Universal Unique Identifier</a> for more details. * <p> * Due to a lack of functionality in Java, a part of the UUID is a secure * random. This results in a long processing time when this method is called * for the first time. */ public String nextUUID() { // TODO: this method has to be checked for it's correctness. I'm not sure the standard is // implemented correctly. // the count of 100-nanosecond intervals since 00:00:00.00 15 October 1582 BigInteger count; // the number of milliseconds since 1 January 1970 BigInteger current = BigInteger.valueOf(System.currentTimeMillis()); // the number of milliseconds since 15 October 1582 BigInteger countMillis = current.subtract(countStart); // the result count = countMillis.multiply(BigInteger.valueOf(10000)); byte[] bits = leftZeroPadString(count.toString(2), 60).getBytes(); // the time_low field byte[] time_low = new byte[32]; for (int i = 0; i < 32; i++) time_low[i] = bits[bits.length - i - 1]; // the time_mid field byte[] time_mid = new byte[16]; for (int i = 0; i < 16; i++) time_mid[i] = bits[bits.length - 32 - i - 1]; // the time_hi_and_version field byte[] time_hi_and_version = new byte[16]; for (int i = 0; i < 12; i++) time_hi_and_version[i] = bits[bits.length - 48 - i - 1]; time_hi_and_version[12] = ONE; time_hi_and_version[13] = ZERO; time_hi_and_version[14] = ZERO; time_hi_and_version[15] = ZERO; // the clock_seq_low field BigInteger clockSequence = BigInteger.valueOf(clock_sequence); byte[] clock_bits = leftZeroPadString(clockSequence.toString(2), 14).getBytes(); byte[] clock_seq_low = new byte[8]; for (int i = 0; i < 8; i++) { clock_seq_low[i] = clock_bits[clock_bits.length - i - 1]; } // the clock_seq_hi_and_reserved byte[] clock_seq_hi_and_reserved = new byte[8]; for (int i = 0; i < 6; i++) clock_seq_hi_and_reserved[i] = clock_bits[clock_bits.length - 8 - i - 1]; clock_seq_hi_and_reserved[6] = ZERO; clock_seq_hi_and_reserved[7] = ONE; String timeLow = Long.toHexString((new BigInteger(new String(reverseArray(time_low)), 2)).longValue()); timeLow = leftZeroPadString(timeLow, 8); String timeMid = Long.toHexString((new BigInteger(new String(reverseArray(time_mid)), 2)).longValue()); timeMid = leftZeroPadString(timeMid, 4); String timeHiAndVersion = Long.toHexString((new BigInteger(new String(reverseArray(time_hi_and_version)), 2)).longValue()); timeHiAndVersion = leftZeroPadString(timeHiAndVersion, 4); String clockSeqHiAndReserved = Long.toHexString((new BigInteger(new String(reverseArray(clock_seq_hi_and_reserved)), 2)).longValue()); clockSeqHiAndReserved = leftZeroPadString(clockSeqHiAndReserved, 2); String clockSeqLow = Long.toHexString((new BigInteger(new String(reverseArray(clock_seq_low)), 2)).longValue()); clockSeqLow = leftZeroPadString(clockSeqLow, 2); long nodeValue = secureRandom.nextLong(); nodeValue = Math.abs(nodeValue); while (nodeValue > 140737488355328L) { nodeValue = secureRandom.nextLong(); nodeValue = Math.abs(nodeValue); } BigInteger nodeInt = BigInteger.valueOf(nodeValue); byte[] node_bits = leftZeroPadString(nodeInt.toString(2), 47).getBytes(); byte[] node = new byte[48]; for (int i = 0; i < 47; i++) node[i] = node_bits[node_bits.length - i - 1]; node[47] = ONE; String theNode = Long.toHexString((new BigInteger(new String(reverseArray(node)), 2)).longValue()); theNode = leftZeroPadString(theNode, 12); StringBuffer result = new StringBuffer(timeLow); result.append("-"); result.append(timeMid); result.append("-"); result.append(timeHiAndVersion); result.append("-"); result.append(clockSeqHiAndReserved); result.append(clockSeqLow); result.append("-"); result.append(theNode); return result.toString().toUpperCase(); } private static byte[] reverseArray(byte[] bits) { byte[] result = new byte[bits.length]; for (int i = 0; i < result.length; i++) result[i] = bits[result.length - 1 - i]; return result; } }
7,673
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/TypeDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.BeanUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.cache.MethodCache; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import java.io.Serializable; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * A TypeDesc represents a Java&lt;-&gt;XML data binding. It is essentially * a collection of FieldDescs describing how to map each field in a Java * class to XML. * * @author Glen Daniels (gdaniels@apache.org) */ public class TypeDesc implements Serializable { public static final Class [] noClasses = new Class [] {}; public static final Object[] noObjects = new Object[] {}; /** A map of {class -> TypeDesc}} */ private static Map classMap = Collections.synchronizedMap(new WeakHashMap()); /** Have we already introspected for the special "any" property desc? */ private boolean lookedForAny = false; /** Can this instance search for metadata in parents of the type it describes? */ private boolean canSearchParents = true; private boolean hasSearchedParents = false; /** My superclass TypeDesc */ private TypeDesc parentDesc = null; protected static Log log = LogFactory.getLog(TypeDesc.class.getName()); /** * Creates a new <code>TypeDesc</code> instance. The type desc can search * the metadata of its type'sparent classes. * * @param javaClass a <code>Class</code> value */ public TypeDesc(Class javaClass) { this(javaClass, true); } /** * Creates a new <code>TypeDesc</code> instance. * * @param javaClass a <code>Class</code> value * @param canSearchParents whether the type desc can search the metadata of * its type's parent classes. */ public TypeDesc(Class javaClass, boolean canSearchParents) { this.javaClassRef = new WeakReference(javaClass); this.canSearchParents = canSearchParents; Class cls = javaClass.getSuperclass(); if (cls != null && !cls.getName().startsWith("java.")) { parentDesc = getTypeDescForClass(cls); } } /** * Static function to explicitly register a type description for * a given class. * * @param cls the Class we're registering metadata about * @param td the TypeDesc containing the metadata */ public static void registerTypeDescForClass(Class cls, TypeDesc td) { classMap.put(cls, td); } /** * Static function for centralizing access to type metadata for a * given class. * * This checks for a static getTypeDesc() method on the * class or _Helper class. * Eventually we may extend this to provide for external * metadata config (via files sitting in the classpath, etc). * */ public static TypeDesc getTypeDescForClass(Class cls) { // First see if we have one explicitly registered // or cached from previous lookup TypeDesc result = (TypeDesc)classMap.get(cls); if (result == null) { try { Method getTypeDesc = MethodCache.getInstance().getMethod(cls, "getTypeDesc", noClasses); if (getTypeDesc != null) { result = (TypeDesc)getTypeDesc.invoke(null, noObjects); if (result != null) { classMap.put(cls, result); } } } catch (Exception e) { } } return result; } /** WeakReference to the Java class for this type */ private WeakReference javaClassRef = null; /** The XML type QName for this type */ private QName xmlType = null; /** The various fields in here */ private FieldDesc [] fields; /** A cache of FieldDescs by name */ private HashMap fieldNameMap = new HashMap(); /** A cache of FieldDescs by Element QName */ private HashMap fieldElementMap = null; /** Are there any fields which are serialized as attributes? */ private boolean _hasAttributes = false; /** Introspected property descriptors */ private BeanPropertyDescriptor[] propertyDescriptors = null; /** Map with key = property descriptor name, value = descriptor */ private Map propertyMap = null; /** * Indication if this type has support for xsd:any. */ private BeanPropertyDescriptor anyDesc = null; public BeanPropertyDescriptor getAnyDesc() { return anyDesc; } /** * Obtain the current array of FieldDescs */ public FieldDesc[] getFields() { return fields; } public FieldDesc[] getFields(boolean searchParents) { // note that if canSearchParents is false, this is identical // to getFields(), because the parent type's metadata is off // limits for restricted types which are required to provide a // complete description of their content model in their own // metadata, per the XML schema rules for // derivation-by-restriction if (canSearchParents && searchParents && !hasSearchedParents) { // check superclasses if they exist if (parentDesc != null) { FieldDesc [] parentFields = parentDesc.getFields(true); // START FIX http://nagoya.apache.org/bugzilla/show_bug.cgi?id=17188 if (parentFields != null) { if (fields != null) { FieldDesc [] ret = new FieldDesc[parentFields.length + fields.length]; System.arraycopy(parentFields, 0, ret, 0, parentFields.length); System.arraycopy(fields, 0, ret, parentFields.length, fields.length); fields = ret; } else { FieldDesc [] ret = new FieldDesc[parentFields.length]; System.arraycopy(parentFields, 0, ret, 0, parentFields.length); fields = ret; } // END FIX http://nagoya.apache.org/bugzilla/show_bug.cgi?id=17188 } } hasSearchedParents = true; } return fields; } /** * Replace the array of FieldDescs, making sure we keep our convenience * caches in sync. */ public void setFields(FieldDesc [] newFields) { fieldNameMap = new HashMap(); fields = newFields; _hasAttributes = false; fieldElementMap = null; for (int i = 0; i < newFields.length; i++) { FieldDesc field = newFields[i]; if (!field.isElement()) { _hasAttributes = true; } fieldNameMap.put(field.getFieldName(), field); } } /** * Add a new FieldDesc, keeping the convenience fields in sync. */ public void addFieldDesc(FieldDesc field) { if (field == null) { throw new IllegalArgumentException( Messages.getMessage("nullFieldDesc")); } int numFields = 0; if (fields != null) { numFields = fields.length; } FieldDesc [] newFields = new FieldDesc[numFields + 1]; if (fields != null) { System.arraycopy(fields, 0, newFields, 0, numFields); } newFields[numFields] = field; fields = newFields; // Keep track of the field by name for fast lookup fieldNameMap.put(field.getFieldName(), field); if (!_hasAttributes && !field.isElement()) _hasAttributes = true; } /** * Get the QName associated with this field, but only if it's * marked as an element. */ public QName getElementNameForField(String fieldName) { FieldDesc desc = (FieldDesc)fieldNameMap.get(fieldName); if (desc == null) { // check superclasses if they exist // and we are allowed to look if (canSearchParents) { if (parentDesc != null) { return parentDesc.getElementNameForField(fieldName); } } } else if (desc.isElement()) { return desc.getXmlName(); } return null; } /** * Get the QName associated with this field, but only if it's * marked as an attribute. */ public QName getAttributeNameForField(String fieldName) { FieldDesc desc = (FieldDesc)fieldNameMap.get(fieldName); if (desc == null) { // check superclasses if they exist // and we are allowed to look if (canSearchParents) { if (parentDesc != null) { return parentDesc.getAttributeNameForField(fieldName); } } } else if (!desc.isElement()) { QName ret = desc.getXmlName(); if (ret == null) { ret = new QName("", fieldName); } return ret; } return null; } /** * Get the field name associated with this QName, but only if it's * marked as an element. * * If the "ignoreNS" argument is true, just compare localNames. */ public String getFieldNameForElement(QName qname, boolean ignoreNS) { // have we already computed the answer to this question? if (fieldElementMap != null) { String cached = (String) fieldElementMap.get(qname); if (cached != null) return cached; } String result = null; String localPart = qname.getLocalPart(); // check fields in this class for (int i = 0; fields != null && i < fields.length; i++) { FieldDesc field = fields[i]; if (field.isElement()) { QName xmlName = field.getXmlName(); if (localPart.equals(xmlName.getLocalPart())) { if (ignoreNS || qname.getNamespaceURI(). equals(xmlName.getNamespaceURI())) { result = field.getFieldName(); break; } } } } // check superclasses if they exist // and we are allowed to look if (result == null && canSearchParents) { if (parentDesc != null) { result = parentDesc.getFieldNameForElement(qname, ignoreNS); } } // cache the answer away for quicker retrieval next time. if (result != null) { if (fieldElementMap == null) fieldElementMap = new HashMap(); fieldElementMap.put(qname, result); } return result; } /** * Get the field name associated with this QName, but only if it's * marked as an attribute. */ public String getFieldNameForAttribute(QName qname) { String possibleMatch = null; for (int i = 0; fields != null && i < fields.length; i++) { FieldDesc field = fields[i]; if (!field.isElement()) { // It's an attribute, so if we have a solid match, return // its name. if (qname.equals(field.getXmlName())) { return field.getFieldName(); } // Not a solid match, but it's still possible we might match // the default (i.e. QName("", fieldName)) if (qname.getNamespaceURI().equals("") && qname.getLocalPart().equals(field.getFieldName())) { possibleMatch = field.getFieldName(); } } } if (possibleMatch == null && canSearchParents) { // check superclasses if they exist // and we are allowed to look if (parentDesc != null) { possibleMatch = parentDesc.getFieldNameForAttribute(qname); } } return possibleMatch; } /** * Get a FieldDesc by field name. */ public FieldDesc getFieldByName(String name) { FieldDesc ret = (FieldDesc)fieldNameMap.get(name); if (ret == null && canSearchParents) { if (parentDesc != null) { ret = parentDesc.getFieldByName(name); } } return ret; } /** * Do we have any FieldDescs marked as attributes? */ public boolean hasAttributes() { if (_hasAttributes) return true; if (canSearchParents) { if (parentDesc != null) { return parentDesc.hasAttributes(); } } return false; } public QName getXmlType() { return xmlType; } public void setXmlType(QName xmlType) { this.xmlType = xmlType; } /** * Get/Cache the property descriptors * @return PropertyDescriptor */ public BeanPropertyDescriptor[] getPropertyDescriptors() { // Return the propertyDescriptors if already set. // If not set, use BeanUtils.getPd to get the property descriptions. // // Since javaClass is a generated class, there // may be a faster way to set the property descriptions than // using BeanUtils.getPd. But for now calling getPd is sufficient. if (propertyDescriptors == null) { makePropertyDescriptors(); } return propertyDescriptors; } private synchronized void makePropertyDescriptors() { if (propertyDescriptors != null) return; // javaClassRef is a WeakReference. So, our javaClass may have been GC'ed. // Protect against this case... Class javaClass = (Class)javaClassRef.get(); if (javaClass == null) { // could throw a RuntimeException, but instead log error and dummy up descriptors log.error(Messages.getMessage("classGCed")); propertyDescriptors = new BeanPropertyDescriptor[0]; anyDesc = null; lookedForAny = true; return; } propertyDescriptors = BeanUtils.getPd(javaClass, this); if (!lookedForAny) { anyDesc = BeanUtils.getAnyContentPD(javaClass); lookedForAny = true; } } public BeanPropertyDescriptor getAnyContentDescriptor() { if (!lookedForAny) { // javaClassRef is a WeakReference. So, our javaClass may have been GC'ed. // Protect against this case... Class javaClass = (Class)javaClassRef.get(); if (javaClass != null) { anyDesc = BeanUtils.getAnyContentPD(javaClass); } else { log.error(Messages.getMessage("classGCed")); anyDesc = null; } lookedForAny = true; } return anyDesc; } /** * Get/Cache the property descriptor map * @return Map with key=propertyName, value=descriptor */ public Map getPropertyDescriptorMap() { synchronized (this) { // Return map if already set. if (propertyMap != null) { return propertyMap; } // Make sure properties exist if (propertyDescriptors == null) { getPropertyDescriptors(); } // Build the map propertyMap = new HashMap(); for (int i = 0; i < propertyDescriptors.length; i++) { BeanPropertyDescriptor descriptor = propertyDescriptors[i]; propertyMap.put(descriptor.getName(), descriptor); } } return propertyMap; } }
7,674
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/ServiceDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.List; import java.io.Serializable; public interface ServiceDesc extends Serializable { /** * What kind of service is this? * @return */ Style getStyle(); void setStyle(Style style); /** * What kind of use is this? * @return */ Use getUse(); void setUse(Use use); /** * the wsdl file of the service. * When null, it means that the wsdl should be autogenerated * @return filename or null */ String getWSDLFile(); /** * set the wsdl file of the service; this causes the named * file to be returned on a ?wsdl, probe, not introspection * generated wsdl. * @param wsdlFileName filename or null to re-enable introspection */ void setWSDLFile(String wsdlFileName); List getAllowedMethods(); void setAllowedMethods(List allowedMethods); TypeMapping getTypeMapping(); void setTypeMapping(TypeMapping tm); /** * the name of the service */ String getName(); /** * the name of the service * @param name */ void setName(String name); /** * get the documentation for the service */ String getDocumentation(); /** * set the documentation for the service */ void setDocumentation(String documentation); void removeOperationDesc(OperationDesc operation); void addOperationDesc(OperationDesc operation); /** * get all the operations as a list of OperationDescs. * this method triggers an evaluation of the valid operations by * introspection, so use sparingly * @return reference to the operations array. This is not a copy */ ArrayList getOperations(); /** * get all overloaded operations by name * @param methodName * @return null for no match, or an array of OperationDesc objects */ OperationDesc [] getOperationsByName(String methodName); /** * Return an operation matching the given method name. Note that if we * have multiple overloads for this method, we will return the first one. * @return null for no match */ OperationDesc getOperationByName(String methodName); /** * Map an XML QName to an operation. Returns the first one it finds * in the case of mulitple matches. * @return null for no match */ OperationDesc getOperationByElementQName(QName qname); /** * Return all operations which match this QName (i.e. get all the * overloads) * @return null for no match */ OperationDesc [] getOperationsByQName(QName qname); void setNamespaceMappings(List namespaces); String getDefaultNamespace(); void setDefaultNamespace(String namespace); void setProperty(String name, Object value); Object getProperty(String name); String getEndpointURL(); void setEndpointURL(String endpointURL); TypeMappingRegistry getTypeMappingRegistry(); void setTypeMappingRegistry(TypeMappingRegistry tmr); boolean isInitialized(); /** * Determine whether or not this is a "wrapped" invocation, i.e. whether * the outermost XML element of the "main" body element represents a * method call, with the immediate children of that element representing * arguments to the method. * * @return true if this is wrapped (i.e. RPC or WRAPPED style), * false otherwise */ boolean isWrapped(); List getDisallowedMethods(); void setDisallowedMethods(List disallowedMethods); }
7,675
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/FaultDesc.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.description; import javax.xml.namespace.QName; import java.io.Serializable; import java.util.ArrayList; /** * Holds information about a fault for an operation * * @author Glen Daniels (gdaniels@apache.org) * @author Tom Jordahl (tomj@apache.org) */ public class FaultDesc implements Serializable { private String name; private QName qname; private ArrayList parameters; private String className; private QName xmlType; private boolean complex; /** * Default constructor */ public FaultDesc() { } /** * Full constructor */ public FaultDesc(QName qname, String className, QName xmlType, boolean complex) { this.qname = qname; this.className = className; this.xmlType = xmlType; this.complex = complex; } public QName getQName() { return qname; } public void setQName(QName name) { this.qname = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList getParameters() { return parameters; } public void setParameters(ArrayList parameters) { this.parameters = parameters; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public boolean isComplex() { return complex; } public void setComplex(boolean complex) { this.complex = complex; } public QName getXmlType() { return xmlType; } public void setXmlType(QName xmlType) { this.xmlType = xmlType; } public String toString() { return toString(""); } public String toString(String indent) { String text =""; text+= indent + "name: " + getName() + "\n"; text+= indent + "qname: " + getQName() + "\n"; text+= indent + "type: " + getXmlType() + "\n"; text+= indent + "Class: " + getClassName() + "\n"; for (int i=0; parameters != null && i < parameters.size(); i++) { text+= indent +" ParameterDesc[" + i + "]:\n"; text+= indent + ((ParameterDesc)parameters.get(i)).toString(" ") + "\n"; } return text; } }
7,676
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/OperationDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import javax.wsdl.OperationType; import java.io.Serializable; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.HashMap; /** * An OperationDesc is an abstract description of an operation on a service. * * !!! WORK IN PROGRESS * * @author Glen Daniels (gdaniels@apache.org) */ public class OperationDesc implements Serializable { // Constants for "message style" operation patterns. If this OperationDesc // is message style, the Java method will have one of these signatures: // public SOAPBodyElement [] method(SOAPBodyElement []) public static final int MSG_METHOD_BODYARRAY = 1; // public void method(SOAPEnvelope, SOAPEnvelope) public static final int MSG_METHOD_SOAPENVELOPE = 2; // public Element [] method(Element []) public static final int MSG_METHOD_ELEMENTARRAY = 3; // public Document method(Document) public static final int MSG_METHOD_DOCUMENT = 4; public static final int MSG_METHOD_NONCONFORMING = -4; private static final Map mepStringToOperationType = new HashMap(); private static final Map operationTypeToMepString = new HashMap(); static { addMep("request-response", OperationType.REQUEST_RESPONSE); addMep("oneway", OperationType.ONE_WAY); addMep("solicit-response", OperationType.SOLICIT_RESPONSE); addMep("notification", OperationType.NOTIFICATION); } private static void addMep(String mepString, OperationType operationType) { mepStringToOperationType.put(mepString, operationType); operationTypeToMepString.put(operationType, mepString); } protected static Log log = LogFactory.getLog(OperationDesc.class.getName()); /** The service we're a part of */ private ServiceDesc parent; /** Parameter list */ private ArrayList parameters = new ArrayList(); /** The operation name (String, or QName?) */ private String name; /** An XML QName which should dispatch to this method */ private QName elementQName; /** The actual Java method associated with this operation, if known */ private transient Method method; /** This operation's style/use. If null, we default to our parent's */ private Style style = null; private Use use = null; /** The number of "in" params (i.e. IN or INOUT) for this operation */ private int numInParams = 0; /** The number of "out" params (i.e. OUT or INOUT) for this operation */ private int numOutParams = 0; /** A unique SOAPAction value for this operation */ private String soapAction = null; /** Faults for this operation */ private ArrayList faults = null; private ParameterDesc returnDesc = new ParameterDesc(); /** If we're a message-style operation, what's our signature? */ private int messageOperationStyle = -1; /** The documentation for the operation */ private String documentation = null; /** The MEP for this Operation - uses the WSDL4J OperationType for now * but we might want to have our own extensible enum for WSDL 2.0 */ private OperationType mep = OperationType.REQUEST_RESPONSE; /** * Default constructor. */ public OperationDesc() { returnDesc.setMode(ParameterDesc.OUT); returnDesc.setIsReturn(true); } /** * "Complete" constructor */ public OperationDesc(String name, ParameterDesc [] parameters, QName returnQName) { this.name = name; returnDesc.setQName(returnQName); returnDesc.setMode(ParameterDesc.OUT); returnDesc.setIsReturn(true); for (int i = 0; i < parameters.length; i++) { addParameter(parameters[i]); } } /** * Return the operation's name */ public String getName() { return name; } /** * Set the operation's name */ public void setName(String name) { this.name = name; } /** * get the documentation for the operation */ public String getDocumentation() { return documentation; } /** * set the documentation for the operation */ public void setDocumentation(String documentation) { this.documentation = documentation; } public QName getReturnQName() { return returnDesc.getQName(); } public void setReturnQName(QName returnQName) { returnDesc.setQName(returnQName); } public QName getReturnType() { return returnDesc.getTypeQName(); } public void setReturnType(QName returnType) { log.debug("@" + Integer.toHexString(hashCode()) + "setReturnType(" + returnType +")"); returnDesc.setTypeQName(returnType); } public Class getReturnClass() { return returnDesc.getJavaType(); } public void setReturnClass(Class returnClass) { returnDesc.setJavaType(returnClass); } public QName getElementQName() { return elementQName; } public void setElementQName(QName elementQName) { this.elementQName = elementQName; } public ServiceDesc getParent() { return parent; } public void setParent(ServiceDesc parent) { this.parent = parent; } public String getSoapAction() { return soapAction; } public void setSoapAction(String soapAction) { this.soapAction = soapAction; } public void setStyle(Style style) { this.style = style; } /** * Return the style of the operation, defaulting to the parent * ServiceDesc's style if we don't have one explicitly set. */ public Style getStyle() { if (style == null) { if (parent != null) { return parent.getStyle(); } return Style.DEFAULT; // Default } return style; } public void setUse(Use use) { this.use = use; } /** * Return the use of the operation, defaulting to the parent * ServiceDesc's use if we don't have one explicitly set. */ public Use getUse() { if (use == null) { if (parent != null) { return parent.getUse(); } return Use.DEFAULT; // Default } return use; } public void addParameter(ParameterDesc param) { // Should we enforce adding INs then INOUTs then OUTs? param.setOrder(getNumParams()); parameters.add(param); if ((param.getMode() == ParameterDesc.IN) || (param.getMode() == ParameterDesc.INOUT)) { numInParams++; } if ((param.getMode() == ParameterDesc.OUT) || (param.getMode() == ParameterDesc.INOUT)) { numOutParams++; } log.debug("@" + Integer.toHexString(hashCode()) + " added parameter >" + param + "@" + Integer.toHexString(param.hashCode()) + "<total parameters:" +getNumParams()); } public void addParameter(QName paramName, QName xmlType, Class javaType, byte parameterMode, boolean inHeader, boolean outHeader) { ParameterDesc param = new ParameterDesc(paramName, parameterMode, xmlType, javaType, inHeader, outHeader); addParameter(param); } public ParameterDesc getParameter(int i) { if (parameters.size() <= i) return null; return (ParameterDesc)parameters.get(i); } public ArrayList getParameters() { return parameters; } /** * Set the parameters wholesale. * * @param newParameters an ArrayList of ParameterDescs */ public void setParameters(ArrayList newParameters) { parameters = new ArrayList(); //Keep numInParams correct. numInParams = 0; numOutParams = 0; for( java.util.ListIterator li= newParameters.listIterator(); li.hasNext(); ){ addParameter((ParameterDesc) li.next()); } } public int getNumInParams() { return numInParams; } public int getNumOutParams() { return numOutParams; } public int getNumParams() { return parameters.size(); } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } /** * Is the return value in the header of the response message? */ public boolean isReturnHeader() { return returnDesc.isOutHeader(); } /** * Set whether the return value is in the response message. */ public void setReturnHeader(boolean value) { returnDesc.setOutHeader(value); } public ParameterDesc getParamByQName(QName qname) { for (Iterator i = parameters.iterator(); i.hasNext();) { ParameterDesc param = (ParameterDesc) i.next(); if (param.getQName().equals(qname)) return param; } return null; } public ParameterDesc getInputParamByQName(QName qname) { ParameterDesc param = null; param = getParamByQName(qname); if ((param == null) || (param.getMode() == ParameterDesc.OUT)) { param = null; } return param; } public ParameterDesc getOutputParamByQName(QName qname) { ParameterDesc param = null; for (Iterator i = parameters.iterator(); i.hasNext();) { ParameterDesc pnext = (ParameterDesc)i.next(); if (pnext.getQName().equals(qname) && pnext.getMode() != ParameterDesc.IN) { param = pnext; break; } } if (param == null) { if (null == returnDesc.getQName() ){ param= new ParameterDesc( returnDesc); //Create copy param.setQName(qname); } else if ( qname.equals(returnDesc.getQName())) { param = returnDesc; } } return param; } /** * Return a list of ALL "in" params (including INOUTs) * * Note: if we were sure the order went IN-&gt;INOUT-&gt;OUT, we could optimize * this. * * @return */ public ArrayList getAllInParams() { ArrayList result = new ArrayList(); for (Iterator i = parameters.iterator(); i.hasNext();) { ParameterDesc desc = (ParameterDesc) i.next(); if (desc.getMode() != ParameterDesc.OUT) { result.add(desc); } } return result; } /** * Return a list of ALL "out" params (including INOUTs) * * Note: if we were sure the order went IN-&gt;INOUT-&gt;OUT, we could optimize * this. * * @return */ public ArrayList getAllOutParams() { ArrayList result = new ArrayList(); for (Iterator i = parameters.iterator(); i.hasNext();) { ParameterDesc desc = (ParameterDesc) i.next(); if (desc.getMode() != ParameterDesc.IN) { result.add(desc); } } return result; } /** * Returns an ordered list of out params (NOT inouts) */ public ArrayList getOutParams() { ArrayList result = new ArrayList(); for (Iterator i = parameters.iterator(); i.hasNext();) { ParameterDesc desc = (ParameterDesc) i.next(); if (desc.getMode() == ParameterDesc.OUT) { result.add(desc); } } return result; } public void addFault(FaultDesc fault) { if (faults == null) faults = new ArrayList(); faults.add(fault); } public ArrayList getFaults() { return faults; } /** * Returns the FaultDesc for the fault class given. * Returns null if not found. */ public FaultDesc getFaultByClass(Class cls) { if (faults == null || cls == null) { return null; } while (cls != null) { // Check each class in the inheritance hierarchy, stopping at // java.* or javax.* classes. for (Iterator iterator = faults.iterator(); iterator.hasNext();) { FaultDesc desc = (FaultDesc) iterator.next(); if (cls.getName().equals(desc.getClassName())) { return desc; } } cls = cls.getSuperclass(); if (cls != null && (cls.getName().startsWith("java.") || cls.getName().startsWith("javax."))) { cls = null; } } return null; } /** * Returns the FaultDesc for the fault class given. * Returns null if not found. */ public FaultDesc getFaultByClass(Class cls, boolean checkParents) { if (checkParents) { return getFaultByClass(cls); } if (faults == null || cls == null) { return null; } for (Iterator iterator = faults.iterator(); iterator.hasNext();) { FaultDesc desc = (FaultDesc) iterator.next(); if (cls.getName().equals(desc.getClassName())) { return desc; } } return null; } /** * Returns the FaultDesc for a QName (which is typically found * in the details element of a SOAP fault). * Returns null if not found. */ public FaultDesc getFaultByQName(QName qname) { if (faults != null) { for (Iterator iterator = faults.iterator(); iterator.hasNext();) { FaultDesc desc = (FaultDesc) iterator.next(); if (qname.equals(desc.getQName())) { return desc; } } } return null; } /** * Returns the FaultDesc for an XMLType. * Returns null if not found. */ public FaultDesc getFaultByXmlType(QName xmlType) { if (faults != null) { for (Iterator iterator = faults.iterator(); iterator.hasNext();) { FaultDesc desc = (FaultDesc) iterator.next(); if (xmlType.equals(desc.getXmlType())) { return desc; } } } return null; } public ParameterDesc getReturnParamDesc() { return returnDesc; } public String toString() { return toString(""); } public String toString(String indent) { String text =""; text+=indent+"name: " + getName() + "\n"; text+=indent+"returnQName: " + getReturnQName() + "\n"; text+=indent+"returnType: " + getReturnType() + "\n"; text+=indent+"returnClass: " + getReturnClass() + "\n"; text+=indent+"elementQName:" + getElementQName() + "\n"; text+=indent+"soapAction: " + getSoapAction() + "\n"; text+=indent+"style: " + getStyle().getName() + "\n"; text+=indent+"use: " + getUse().getName() + "\n"; text+=indent+"numInParams: " + getNumInParams() + "\n"; text+=indent+"method:" + getMethod() + "\n"; for (int i=0; i<parameters.size(); i++) { text+=indent+" ParameterDesc[" + i + "]:\n"; text+=indent+ ((ParameterDesc)parameters.get(i)).toString(" ") + "\n"; } if (faults != null) { for (int i=0; i<faults.size(); i++) { text+=indent+" FaultDesc[" + i + "]:\n"; text+=indent+ ((FaultDesc)faults.get(i)).toString(" ") + "\n"; } } return text; } public int getMessageOperationStyle() { return messageOperationStyle; } public void setMessageOperationStyle(int messageOperationStyle) { this.messageOperationStyle = messageOperationStyle; } public OperationType getMep() { return mep; } public void setMep(OperationType mep) { this.mep = mep; } /** * Get the MEP as a string. * * @return the string representation of the MEP */ public String getMepString() { return (String)operationTypeToMepString.get(mep); } /** * Set the MEP using a string like "request-response" * @param mepString */ public void setMep(String mepString) { OperationType newMep = (OperationType)mepStringToOperationType.get(mepString); if (newMep != null) { mep = newMep; } } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (method != null){ out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } else { out.writeObject(null); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{ in.defaultReadObject(); Class clazz = (Class) in.readObject(); if (clazz != null){ String methodName = (String) in.readObject(); Class[] parameterTypes = (Class[]) in.readObject(); try { method = clazz.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { throw new IOException("Unable to deserialize the operation's method: "+ methodName); } } } }
7,677
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/JavaServiceDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import org.apache.axis.AxisServiceConfig; import org.apache.axis.Constants; import org.apache.axis.InternalException; import org.apache.axis.AxisProperties; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.*; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.message.SOAPBodyElement; import org.apache.axis.message.SOAPEnvelope; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.axis.utils.bytecode.ParamNameExtractor; import org.apache.axis.wsdl.Skeleton; import org.apache.axis.wsdl.fromJava.Namespaces; import org.apache.commons.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.namespace.QName; import javax.xml.rpc.holders.Holder; 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.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; /** * A ServiceDesc is an abstract description of a service. * * ServiceDescs contain OperationDescs, which are descriptions of operations. * The information about a service's operations comes from one of two places: * 1) deployment, or 2) introspection. * * @author Glen Daniels (gdaniels@apache.org) */ public class JavaServiceDesc implements ServiceDesc { protected static Log log = LogFactory.getLog(JavaServiceDesc.class.getName()); /** The name of this service */ private String name = null; /** The documentation of this service */ private String documentation = null; /** Style/Use */ private Style style = Style.RPC; private Use use = Use.ENCODED; // Style and Use are related. By default, if Style==RPC, Use should be // ENCODED. But if Style==DOCUMENT, Use should be LITERAL. So we want // to keep the defaults synced until someone explicitly sets the Use. private boolean useSet = false; /** Our operations - a list of OperationDescs */ private ArrayList operations = new ArrayList(); /** A collection of namespaces which will map to this service */ private List namespaceMappings = null; /** * Where does our WSDL document live? If this is non-null, the "?WSDL" * generation will automatically return this file instead of dynamically * creating a WSDL. BE CAREFUL because this means that Handlers will * not be able to add to the WSDL for extensions/headers.... */ private String wsdlFileName = null; /** * An endpoint URL which someone has specified for this service. If * this is set, WSDL generation will pick it up instead of defaulting * to the transport URL. */ private String endpointURL = null; /** Place to store user-extensible service-related properties */ private HashMap properties = null; /** Lookup caches */ private HashMap name2OperationsMap = null; private HashMap qname2OperationsMap = null; private transient HashMap method2OperationMap = new HashMap(); // THE FOLLOWING STUFF IS ALL JAVA-SPECIFIC, AND WILL BE FACTORED INTO // A JAVA-SPECIFIC SUBCLASS. --Glen /** List of allowed methods */ /** null allows everything, an empty ArrayList allows nothing */ private List allowedMethods = null; /** List if disallowed methods */ private List disallowedMethods = null; /** Implementation class */ private Class implClass = null; /** * Is the implementation a Skeleton? If this is true, it will generate * a Fault to provide OperationDescs via WSDD. */ private boolean isSkeletonClass = false; /** Cached copy of the skeleton "getOperationDescByName" method */ private transient Method skelMethod = null; /** Classes at which we should stop looking up the inheritance chain * when introspecting */ private ArrayList stopClasses = null; /** Lookup caches */ private transient HashMap method2ParamsMap = new HashMap(); private OperationDesc messageServiceDefaultOp = null; /** Method names for which we have completed any introspection necessary */ private ArrayList completedNames = new ArrayList(); /** Our typemapping for resolving Java&lt;-&gt;XML type issues */ private TypeMapping tm = null; private TypeMappingRegistry tmr = null; private boolean haveAllSkeletonMethods = false; private boolean introspectionComplete = false; /** * Default constructor */ public JavaServiceDesc() { } /** * What kind of service is this? * @return */ public Style getStyle() { return style; } public void setStyle(Style style) { this.style = style; if (!useSet) { // Use hasn't been explicitly set, so track style use = style == Style.RPC ? Use.ENCODED : Use.LITERAL; } } /** * What kind of use is this? * @return */ public Use getUse() { return use; } public void setUse(Use use) { useSet = true; this.use = use; } /** * Determine whether or not this is a "wrapped" invocation, i.e. whether * the outermost XML element of the "main" body element represents a * method call, with the immediate children of that element representing * arguments to the method. * * @return true if this is wrapped (i.e. RPC or WRAPPED style), * false otherwise */ public boolean isWrapped() { return ((style == Style.RPC) || (style == Style.WRAPPED)); } /** * the wsdl file of the service. * When null, it means that the wsdl should be autogenerated * @return filename or null */ public String getWSDLFile() { return wsdlFileName; } /** * set the wsdl file of the service; this causes the named * file to be returned on a ?wsdl, probe, not introspection * generated wsdl. * @param wsdlFileName filename or null to re-enable introspection */ public void setWSDLFile(String wsdlFileName) { this.wsdlFileName = wsdlFileName; } public List getAllowedMethods() { return allowedMethods; } public void setAllowedMethods(List allowedMethods) { this.allowedMethods = allowedMethods; } public Class getImplClass() { return implClass; } /** * set the implementation class * <p> * Warning: You cannot call getInitializedServiceDesc() after setting this * as it uses this to indicate its work has already been done. * * @param implClass * @throws IllegalArgumentException if the implementation class is already * set */ public void setImplClass(Class implClass) { if (this.implClass != null) throw new IllegalArgumentException( Messages.getMessage("implAlreadySet")); this.implClass = implClass; if (Skeleton.class.isAssignableFrom(implClass)) { isSkeletonClass = true; loadSkeletonOperations(); } } private void loadSkeletonOperations() { Method method = null; try { method = implClass.getDeclaredMethod("getOperationDescs", new Class [] {}); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } if (method == null) { // FIXME : Throw an error? return; } try { Collection opers = (Collection)method.invoke(implClass, null); for (Iterator i = opers.iterator(); i.hasNext();) { OperationDesc skelDesc = (OperationDesc)i.next(); addOperationDesc(skelDesc); } } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } catch (IllegalArgumentException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } haveAllSkeletonMethods = true; } public TypeMapping getTypeMapping() { if(tm == null) { return DefaultTypeMappingImpl.getSingletonDelegate(); // throw new RuntimeException(Messages.getMessage("noDefaultTypeMapping00")); } return tm; } public void setTypeMapping(TypeMapping tm) { this.tm = tm; } /** * the name of the service */ public String getName() { return name; } /** * the name of the service * @param name */ public void setName(String name) { this.name = name; } /** * get the documentation for the service */ public String getDocumentation() { return documentation; } /** * set the documentation for the service */ public void setDocumentation(String documentation) { this.documentation = documentation; } public ArrayList getStopClasses() { return stopClasses; } public void setStopClasses(ArrayList stopClasses) { this.stopClasses = stopClasses; } public List getDisallowedMethods() { return disallowedMethods; } public void setDisallowedMethods(List disallowedMethods) { this.disallowedMethods = disallowedMethods; } public void removeOperationDesc(OperationDesc operation) { operations.remove(operation); operation.setParent(null); if (name2OperationsMap != null) { String name = operation.getName(); ArrayList overloads = (ArrayList)name2OperationsMap.get(name); if (overloads != null) { overloads.remove(operation); if (overloads.size() == 0) { name2OperationsMap.remove(name); } } } if (qname2OperationsMap != null) { QName qname = operation.getElementQName(); ArrayList list = (ArrayList)qname2OperationsMap.get(qname); if (list != null) { list.remove(operation); } } if (method2OperationMap != null) { Method method = operation.getMethod(); if (method != null) { method2OperationMap.remove(method); } } } public void addOperationDesc(OperationDesc operation) { operations.add(operation); operation.setParent(this); if (name2OperationsMap == null) { name2OperationsMap = new HashMap(); } // Add name to name2Operations Map String name = operation.getName(); ArrayList overloads = (ArrayList)name2OperationsMap.get(name); if (overloads == null) { overloads = new ArrayList(); name2OperationsMap.put(name, overloads); } else if (JavaUtils.isTrue( AxisProperties.getProperty(Constants.WSIBP11_COMPAT_PROPERTY)) && overloads.size() > 0) { throw new RuntimeException(Messages.getMessage("noOverloadedOperations", name)); } overloads.add(operation); } /** * get all the operations as a list of OperationDescs. * this method triggers an evaluation of the valid operations by * introspection, so use sparingly * @return reference to the operations array. This is not a copy */ public ArrayList getOperations() { loadServiceDescByIntrospection(); // Just in case... return operations; } /** * get all overloaded operations by name * @param methodName * @return null for no match, or an array of OperationDesc objects */ public OperationDesc [] getOperationsByName(String methodName) { getSyncedOperationsForName(implClass, methodName); if (name2OperationsMap == null) return null; ArrayList overloads = (ArrayList)name2OperationsMap.get(methodName); if (overloads == null) { return null; } OperationDesc [] array = new OperationDesc [overloads.size()]; return (OperationDesc[])overloads.toArray(array); } /** * Return an operation matching the given method name. Note that if we * have multiple overloads for this method, we will return the first one. * @return null for no match */ public OperationDesc getOperationByName(String methodName) { // If we need to load up operations from introspection data, do it. // This returns fast if we don't need to do anything, so it's not very // expensive. getSyncedOperationsForName(implClass, methodName); if (name2OperationsMap == null) return null; ArrayList overloads = (ArrayList)name2OperationsMap.get(methodName); if (overloads == null) { return null; } return (OperationDesc)overloads.get(0); } /** * Map an XML QName to an operation. Returns the first one it finds * in the case of mulitple matches. * @return null for no match */ public OperationDesc getOperationByElementQName(QName qname) { OperationDesc [] overloads = getOperationsByQName(qname); // Return the first one.... if ((overloads != null) && overloads.length > 0) return overloads[0]; return null; } /** * Return all operations which match this QName (i.e. get all the * overloads) * @return null for no match */ public OperationDesc [] getOperationsByQName(QName qname) { // Look in our mapping of QNames -> operations. // But first, let's make sure we've initialized said mapping.... initQNameMap(); ArrayList overloads = (ArrayList)qname2OperationsMap.get(qname); if (overloads == null) { // Nothing specifically matching this QName. if (name2OperationsMap != null) { if ((isWrapped() || ((style == Style.MESSAGE) && (getDefaultNamespace() == null)))) { // Try ignoring the namespace....? overloads = (ArrayList) name2OperationsMap.get(qname.getLocalPart()); } else { // TODO the above code is weird: a JavaServiceDesc can be document or rpc and // still define a WSDL operation using a wrapper style mapping. // The following code handles this case. Object ops = name2OperationsMap.get(qname.getLocalPart()); if (ops != null) { overloads = new ArrayList((Collection) ops); for (Iterator iter = overloads.iterator(); iter.hasNext();) { OperationDesc operationDesc = (OperationDesc) iter.next(); if (Style.WRAPPED != operationDesc.getStyle()) { iter.remove(); } } } } } // Handle the case where a single Message-style operation wants // to accept anything. if ((style == Style.MESSAGE) && (messageServiceDefaultOp != null)) return new OperationDesc [] { messageServiceDefaultOp }; if (overloads == null) return null; } getSyncedOperationsForName(implClass, ((OperationDesc)overloads.get(0)).getName()); // Convert to array before sorting to avoid concurrency issues OperationDesc[] array = (OperationDesc[])overloads.toArray( new OperationDesc[overloads.size()]); // Sort the overloads by number of arguments - prevents us calling methods // with more parameters than supplied in the request (with missing parameters // defaulted to null) when a perfectly good method exists with exactly the // supplied parameters. Arrays.sort(array, new Comparator() { public int compare(Object o1, Object o2) { Method meth1 = ((OperationDesc)o1).getMethod(); Method meth2 = ((OperationDesc)o2).getMethod(); return (meth1.getParameterTypes().length - meth2.getParameterTypes().length); } }); return array; } private synchronized void initQNameMap() { if (qname2OperationsMap == null) { loadServiceDescByIntrospection(); qname2OperationsMap = new HashMap(); for (Iterator i = operations.iterator(); i.hasNext();) { OperationDesc operationDesc = (OperationDesc) i.next(); QName qname = operationDesc.getElementQName(); ArrayList list = (ArrayList)qname2OperationsMap.get(qname); if (list == null) { list = new ArrayList(); qname2OperationsMap.put(qname, list); } list.add(operationDesc); } } } /** * Synchronize an existing OperationDesc to a java.lang.Method. * * This method is used when the deployer has specified operation metadata * and we want to match that up with a real java Method so that the * Operation-level dispatch carries us all the way to the implementation. * Search the declared methods on the implementation class to find one * with an argument list which matches our parameter list. */ private void syncOperationToClass(OperationDesc oper, Class implClass) { // ------------------------------------------------ // Developer Note: // // The goal of the sync code is to associate // the OperationDesc/ParamterDesc with the // target Method. There are a number of ways to get to this // point depending on what information // is available. Here are the main scenarios: // // A) Deployment with wsdd (non-skeleton): // * OperationDesc/ParameterDesc loaded from deploy.wsdd // * Loaded ParameterDesc does not have javaType, // so it is discovered using the TypeMappingRegistry // (also loaded via deploy.wsdd) and the // typeQName specified by the ParameterDesc. // * Sync occurs using the discovered // javaTypes and the javaTypes of the Method // parameters // // B) Deployment with no wsdd OperationDesc info (non-skeleton): // * Implementation Class introspected to build // OperationDesc/ParameterDesc. // * ParameterDesc is known via introspection. // * ParameterDesc are discovered using javaType // and TypeMappingRegistry. // * Sync occurs using the introspected // javaTypes and the javaTypes of the Method // parameters // // C) Deployment with wsdd (skeleton): // * OperationDesc/ParameterDesc loaded from the Skeleton // * In this scenario the ParameterDescs' already // have javaTypes (see E below). // * Sync occurs using the ParameterDesc // javaTypes and the javaTypes of the Method // parameters. // // D) Commandline Java2WSDL loading non-Skeleton Class/Interface // * Class/Interface introspected to build // OperationDesc/ParameterDesc. // * The javaTypes of the ParameterDesc are set using introspection. // * typeQNames are determined for built-in types using // from the default TypeMappingRegistry. Other // typeQNames are guessed from the javaType. Note // that there is no loaded TypeMappingRegistry. // * Sync occurs using the ParameterDesc // javaTypes and the javaTypes of the Method // parameters. // // E) Commandline Java2WSDL loading Skeleton Class // * OperationDesc/ParameterDesc loaded from Skeleton // * Each ParameterDesc has an appropriate typeQName // * Each ParameterDesc also has a javaType, which is // essential for sync'ing up with the // method since there is no loaded TypeMappingRegistry. // * Syncronization occurs using the ParameterDesc // javaTypes and the javaTypes of the Method // parameters. // // So in each scenario, the ultimate sync'ing occurs // using the javaTypes of the ParameterDescs and the // javaTypes of the Method parameters. // // ------------------------------------------------ // If we're already mapped to a Java method, no need to do anything. if (oper.getMethod() != null) return; // Find the method. We do this once for each Operation. Method[] methods = getMethods(implClass); // A place to keep track of possible matches Method possibleMatch = null; for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(oper.getName()) && method2OperationMap.get(method) == null) { if (style == Style.MESSAGE) { int messageOperType = checkMessageMethod(method); if(messageOperType == OperationDesc.MSG_METHOD_NONCONFORMING) continue; if (messageOperType == -1) { throw new InternalException("Couldn't match method to any of the allowable message-style patterns!"); } oper.setMessageOperationStyle(messageOperType); // Don't bother checking params if we're message style possibleMatch = method; break; } // Check params Class [] paramTypes = method.getParameterTypes(); if (paramTypes.length != oper.getNumParams()) continue; int j; boolean conversionNecessary = false; for (j = 0; j < paramTypes.length; j++) { Class type = paramTypes[j]; Class actualType = type; if (Holder.class.isAssignableFrom(type)) { actualType = JavaUtils.getHolderValueType(type); } ParameterDesc param = oper.getParameter(j); QName typeQName = param.getTypeQName(); if (typeQName == null) { // No typeQName is available. Set it using // information from the actual type. // (Scenarios B and D) // There is no need to try and match with // the Method parameter javaType because // the ParameterDesc is being constructed // by introspecting the Method. typeQName = getTypeMapping().getTypeQName(actualType); param.setTypeQName(typeQName); } else { // A type qname is available. // Ensure that the ParameterDesc javaType // is convertable to the Method parameter type // // Use the available javaType (Scenarios C and E) // or get one from the TMR (Scenario A). Class paramClass = param.getJavaType(); if (paramClass != null && JavaUtils.getHolderValueType(paramClass) != null) { paramClass = JavaUtils.getHolderValueType(paramClass); } if (paramClass == null) { paramClass = getTypeMapping().getClassForQName(param.getTypeQName(), type); } if (paramClass != null) { // This is a match if the paramClass is somehow // convertable to the "real" parameter type. If not, // break out of this loop. if (!JavaUtils.isConvertable(paramClass, actualType)) { break; } if (!actualType.isAssignableFrom(paramClass)) { // This doesn't fit without conversion conversionNecessary = true; } } } // In all scenarios the ParameterDesc javaType is set to // match the javaType in the corresponding parameter. // This is essential. param.setJavaType(type); } if (j != paramTypes.length) { // failed. continue; } // This is our latest possibility possibleMatch = method; // If this is exactly it, stop now. Otherwise keep looking // just in case we find a better match. if (!conversionNecessary) { break; } } } // At this point, we may or may not have a possible match. // FIXME : Should we prefer an exact match from a base class over // a with-conversion match from the target class? If so, // we'll need to change the logic below. if (possibleMatch != null) { Class returnClass = possibleMatch.getReturnType(); oper.setReturnClass(returnClass); QName returnType = oper.getReturnType(); if (returnType == null) { oper.setReturnType(getTypeMapping().getTypeQName(returnClass)); } // Do the faults createFaultMetadata(possibleMatch, oper); oper.setMethod(possibleMatch); method2OperationMap.put(possibleMatch, oper); return; } // Didn't find a match. Try the superclass, if appropriate Class superClass = implClass.getSuperclass(); if (superClass != null && !superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.") && (stopClasses == null || !stopClasses.contains(superClass.getName()))) { syncOperationToClass(oper, superClass); } // Exception if sync fails to find method for operation if (oper.getMethod() == null) { InternalException ie = new InternalException(Messages.getMessage("serviceDescOperSync00", oper.getName(), implClass.getName())); throw ie; } } private Method[] getMethods(Class implClass) { if (implClass.isInterface()){ // only return methods that are not part of start classes List methodsList = new ArrayList(); Method[] methods = implClass.getMethods(); if (methods != null) { for (int i = 0; i < methods.length; i++) { String declaringClass = methods[i].getDeclaringClass().getName(); if (!declaringClass.startsWith("java.") && !declaringClass.startsWith("javax.")) { methodsList.add(methods[i]); } } } return (Method[])methodsList.toArray(new Method[]{}); } else { return implClass.getDeclaredMethods(); } } private int checkMessageMethod(Method method) { // Collect the types so we know what we're dealing with in the target // method. Class [] params = method.getParameterTypes(); if (params.length == 1) { if ((params[0] == Element[].class) && (method.getReturnType() == Element[].class)) { return OperationDesc.MSG_METHOD_ELEMENTARRAY; } if ((params[0] == SOAPBodyElement[].class) && (method.getReturnType() == SOAPBodyElement[].class)) { return OperationDesc.MSG_METHOD_BODYARRAY; } if ((params[0] == Document.class) && (method.getReturnType() == Document.class)) { return OperationDesc.MSG_METHOD_DOCUMENT; } } else if (params.length == 2) { if (((params[0] == SOAPEnvelope.class) && (params[1] == SOAPEnvelope.class)) || ((params[0] == javax.xml.soap.SOAPEnvelope.class) && (params[1] == javax.xml.soap.SOAPEnvelope.class)) && (method.getReturnType() == void.class)){ return OperationDesc.MSG_METHOD_SOAPENVELOPE; } } if( null != allowedMethods && !allowedMethods.isEmpty() ) throw new InternalException (Messages.getMessage("badMsgMethodParams", method.getName())); return OperationDesc.MSG_METHOD_NONCONFORMING; } /** * Fill in a service description by introspecting the implementation * class. */ public void loadServiceDescByIntrospection() { loadServiceDescByIntrospection(implClass); // Setting this to null means there is nothing more to do, and it // avoids future string compares. completedNames = null; } /** * Fill in a service description by introspecting the implementation * class. */ public void loadServiceDescByIntrospection(Class implClass) { if (introspectionComplete || implClass == null) { return; } // set the implementation class for the service description this.implClass = implClass; if (Skeleton.class.isAssignableFrom(implClass)) { isSkeletonClass = true; loadSkeletonOperations(); } /** If the class knows what it should be exporting, * respect its wishes. */ AxisServiceConfig axisConfig = null; try { Method method = implClass.getDeclaredMethod( "getAxisServiceConfig", new Class [] {}); if (method != null && Modifier.isStatic(method.getModifiers())) { axisConfig = (AxisServiceConfig)method.invoke(null, null); } } catch (Exception e) { // No problem, just continue without... } if (axisConfig != null) { String allowedMethodsStr = axisConfig.getAllowedMethods(); if (allowedMethodsStr != null && !"*".equals(allowedMethodsStr)) { ArrayList methodList = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(allowedMethodsStr, " ,"); while (tokenizer.hasMoreTokens()) { methodList.add(tokenizer.nextToken()); } setAllowedMethods(methodList); } } loadServiceDescByIntrospectionRecursive(implClass); // All operations should now be synchronized. Check it. for (Iterator iterator = operations.iterator(); iterator.hasNext();) { OperationDesc operation = (OperationDesc) iterator.next(); if (operation.getMethod() == null) { throw new InternalException( Messages.getMessage("badWSDDOperation", operation.getName(), "" + operation.getNumParams())); } } if ((style == Style.MESSAGE) && operations.size() == 1) { messageServiceDefaultOp = (OperationDesc)operations.get(0); } introspectionComplete = true; } /** * Is this method from ServiceLifeCycle interface? * @param m * @return true if this method is from ServiceLifeCycle interface */ private boolean isServiceLifeCycleMethod(Class implClass, Method m) { if(javax.xml.rpc.server.ServiceLifecycle.class.isAssignableFrom(implClass)) { String methodName = m.getName(); if(methodName.equals("init")) { // Check if the method signature is // "public abstract void init(Object context) throws ServiceException;" Class[] classes = m.getParameterTypes(); if(classes != null && classes.length == 1 && classes[0] == Object.class && m.getReturnType() == Void.TYPE) { return true; } } else if (methodName.equals("destroy")){ // Check if the method signature is // "public abstract void destroy();" Class[] classes = m.getParameterTypes(); if(classes != null && classes.length == 0 && m.getReturnType() == Void.TYPE) { return true; } } } return false; } /** * Recursive helper class for loadServiceDescByIntrospection */ private void loadServiceDescByIntrospectionRecursive(Class implClass) { if (Skeleton.class.equals(implClass)) { return; } Method [] methods = getMethods(implClass); for (int i = 0; i < methods.length; i++) { if (Modifier.isPublic(methods[i].getModifiers()) && !isServiceLifeCycleMethod(implClass, methods[i])) { getSyncedOperationsForName(implClass, methods[i].getName()); } } if (implClass.isInterface()) { Class [] superClasses = implClass.getInterfaces(); for (int i = 0; i < superClasses.length; i++) { Class superClass = superClasses[i]; if (!superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.") && (stopClasses == null || !stopClasses.contains(superClass.getName()))) { loadServiceDescByIntrospectionRecursive(superClass); } } } else { Class superClass = implClass.getSuperclass(); if (superClass != null && !superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.") && (stopClasses == null || !stopClasses.contains(superClass.getName()))) { loadServiceDescByIntrospectionRecursive(superClass); } } } /** * Fill in a service description by introspecting the implementation * class. This version takes the implementation class and the in-scope * TypeMapping. */ public void loadServiceDescByIntrospection(Class cls, TypeMapping tm) { // Should we complain if the implClass changes??? implClass = cls; this.tm = tm; if (Skeleton.class.isAssignableFrom(implClass)) { isSkeletonClass = true; loadSkeletonOperations(); } loadServiceDescByIntrospection(); } /** * Makes sure we have completely synchronized OperationDescs with * the implementation class. */ private void getSyncedOperationsForName(Class implClass, String methodName) { // If we're a Skeleton deployment, skip the statics. if (isSkeletonClass) { if (methodName.equals("getOperationDescByName") || methodName.equals("getOperationDescs")) return; } // If we have no implementation class, don't worry about it (we're // probably on the client) if (implClass == null) return; // If we're done introspecting, or have completed this method, return if (completedNames == null || completedNames.contains(methodName)) return; // Skip it if it's not a sanctioned method name if ((allowedMethods != null) && !allowedMethods.contains(methodName)) return; if ((disallowedMethods != null) && disallowedMethods.contains(methodName)) return; // If we're a skeleton class, make sure we don't already have any // OperationDescs for this name (as that might cause conflicts), // then load them up from the Skeleton class. if (isSkeletonClass && !haveAllSkeletonMethods) { // FIXME : Check for existing ones and fault if found if (skelMethod == null) { // Grab metadata from the Skeleton for parameter info try { skelMethod = implClass.getDeclaredMethod( "getOperationDescByName", new Class [] { String.class }); } catch (NoSuchMethodException e) { } catch (SecurityException e) { } if (skelMethod == null) { // FIXME : Throw an error? return; } } try { List skelList = (List)skelMethod.invoke(implClass, new Object [] { methodName }); if (skelList != null) { Iterator i = skelList.iterator(); while (i.hasNext()) { addOperationDesc((OperationDesc)i.next()); } } } catch (IllegalAccessException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } catch (IllegalArgumentException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } catch (InvocationTargetException e) { if(log.isDebugEnabled()) { log.debug(Messages.getMessage("exception00"), e); } return; } } // OK, go find any current OperationDescs for this method name and // make sure they're synced with the actual class. if (name2OperationsMap != null) { ArrayList currentOverloads = (ArrayList)name2OperationsMap.get(methodName); if (currentOverloads != null) { // For each one, sync it to the implementation class' methods for (Iterator i = currentOverloads.iterator(); i.hasNext();) { OperationDesc oper = (OperationDesc) i.next(); if (oper.getMethod() == null) { syncOperationToClass(oper, implClass); } } } } // Now all OperationDescs from deployment data have been completely // filled in. So we now make new OperationDescs for any method // overloads which were not covered above. // NOTE : This is the "lenient" approach, which allows you to // specify one overload and still get the others by introspection. // We could equally well return above if we found OperationDescs, // and have a rule that if you specify any overloads, you must specify // all the ones you want accessible. createOperationsForName(implClass, methodName); // Note that we never have to look at this method name again. completedNames.add(methodName); } private String getUniqueOperationName(String name) { int i = 1; String candidate; do { candidate = name + i++; } while (name2OperationsMap.get(candidate) != null); return candidate; } /** * Look for methods matching this name, and for each one, create an * OperationDesc (if it's not already in our list). * * TODO: Make this more efficient */ private void createOperationsForName(Class implClass, String methodName) { // If we're a Skeleton deployment, skip the statics. if (isSkeletonClass) { if (methodName.equals("getOperationDescByName") || methodName.equals("getOperationDescs")) return; } Method [] methods = getMethods(implClass); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(methodName) && !isServiceLifeCycleMethod(implClass, method)) { createOperationForMethod(method); } } Class superClass = implClass.getSuperclass(); if (superClass != null && !superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.") && (stopClasses == null || !stopClasses.contains(superClass.getName()))) { createOperationsForName(superClass, methodName); } } /** * Make an OperationDesc from a Java method. * * In the absence of deployment metadata, this code will introspect a * Method and create an appropriate OperationDesc. If the class * implements the Skeleton interface, we will use the metadata from there * in constructing the OperationDesc. If not, we use parameter names * from the bytecode debugging info if available, or "in0", "in1", etc. * if not. */ private void createOperationForMethod(Method method) { // If we've already got it, never mind if (method2OperationMap.get(method) != null) { return; } Class [] paramTypes = method.getParameterTypes(); // And if we've already got an exact match (i.e. an override), // never mind ArrayList overloads = name2OperationsMap == null ? null : (ArrayList)name2OperationsMap.get(method.getName()); if (overloads != null && !overloads.isEmpty()) { // Search each OperationDesc that already has a Method // associated with it, and check for parameter type equivalence. for (int i = 0; i < overloads.size(); i++) { OperationDesc op = (OperationDesc)overloads.get(i); Method checkMethod = op.getMethod(); if (checkMethod != null) { Class [] others = checkMethod.getParameterTypes(); if (paramTypes.length == others.length) { int j = 0; for (; j < others.length; j++) { if (!others[j].equals(paramTypes[j])) break; } // If we got all the way through, we have a match. if (j == others.length) return; } } } } boolean isWSICompliant = JavaUtils.isTrue( AxisProperties.getProperty(Constants.WSIBP11_COMPAT_PROPERTY)); // Make an OperationDesc, fill in common stuff OperationDesc operation = new OperationDesc(); // If we're WS-I compliant, we can't have overloaded operation names. // If we find duplicates, we generate unique names for them and map // those names to the correct Method. String name = method.getName(); if (isWSICompliant && name2OperationsMap != null) { Collection methodNames = name2OperationsMap.keySet(); name = JavaUtils.getUniqueValue(methodNames, name); } operation.setName(name); String defaultNS = ""; if (namespaceMappings != null && !namespaceMappings.isEmpty()) { // If we have a default namespace mapping, require callers to // use that namespace. defaultNS = (String)namespaceMappings.get(0); } if(defaultNS.length() == 0) { defaultNS = Namespaces.makeNamespace(method.getDeclaringClass().getName()); } operation.setElementQName(new QName(defaultNS, name)); operation.setMethod(method); // If this is a MESSAGE style service, set up the OperationDesc // appropriately. if (style == Style.MESSAGE) { int messageOperType = checkMessageMethod(method); if(messageOperType == OperationDesc.MSG_METHOD_NONCONFORMING) return; if (messageOperType == -1) { throw new InternalException("Couldn't match method to any of the allowable message-style patterns!"); } operation.setMessageOperationStyle(messageOperType); operation.setReturnClass(Object.class); operation.setReturnType(Constants.XSD_ANYTYPE); } else { // For other styles, continue here. Class retClass = method.getReturnType(); operation.setReturnClass(retClass); QName typeQName = getTypeQName(retClass); operation.setReturnType(typeQName); String [] paramNames = getParamNames(method); for (int k = 0; k < paramTypes.length; k++) { Class type = paramTypes[k]; ParameterDesc paramDesc = new ParameterDesc(); // param should be unqualified if we're using rpc style, // or should use the operation's namespace if its document style String paramNamespace = (this.style == Style.RPC ? "" : operation.getElementQName().getNamespaceURI()); // If we have a name for this param, use it, otherwise call // it "in*" if (paramNames != null && paramNames[k] != null && paramNames[k].length()>0) { paramDesc.setQName(new QName(paramNamespace, paramNames[k])); } else { paramDesc.setQName(new QName(paramNamespace, "in" + k)); } // If it's a Holder, mark it INOUT, and set the XML type QName // to the held type. Otherwise it's IN. Class heldClass = JavaUtils.getHolderValueType(type); if (heldClass != null) { paramDesc.setMode(ParameterDesc.INOUT); paramDesc.setTypeQName(getTypeQName(heldClass)); } else { paramDesc.setMode(ParameterDesc.IN); paramDesc.setTypeQName(getTypeQName(type)); } paramDesc.setJavaType(type); operation.addParameter(paramDesc); } } createFaultMetadata(method, operation); addOperationDesc(operation); method2OperationMap.put(method, operation); } private QName getTypeQName(Class javaClass) { QName typeQName; TypeMapping tm = getTypeMapping(); if (style == Style.RPC) { typeQName = tm.getTypeQName(javaClass); } else { typeQName = tm.getTypeQNameExact(javaClass); if (typeQName == null && javaClass.isArray()) { typeQName = tm.getTypeQName(javaClass.getComponentType()); } else { typeQName = tm.getTypeQName(javaClass); } } return typeQName; } private void createFaultMetadata(Method method, OperationDesc operation) { // Create Exception Types Class[] exceptionTypes = method.getExceptionTypes(); for (int i=0; i < exceptionTypes.length; i++) { // Every remote method declares a java.rmi.RemoteException // Only interested in application specific exceptions. // Ignore java and javax package exceptions. Class ex = exceptionTypes[i]; if (ex != java.rmi.RemoteException.class && ex != org.apache.axis.AxisFault.class && !ex.getName().startsWith("java.") && !ex.getName().startsWith("javax.")) { // For JSR 101 v.1.0, there is a simple fault mapping // and a complexType fault mapping...both mappings // generate a class that extends (directly or indirectly) // Exception. // When converting java back to wsdl it is not possible // to determine which way to do the mapping, // so it is always mapped back using the complexType // fault mapping because it is more useful (i.e. it // establishes a hierarchy of exceptions). Note that this // will not cause any roundtripping problems. // Rich /* Old Simple Type Mode Field[] f = ex.getDeclaredFields(); ArrayList exceptionParams = new ArrayList(); for (int j = 0; j < f.length; j++) { int mod = f[j].getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { QName qname = new QName("", f[j].getName()); QName typeQName = tm.getTypeQName(f[j].getType()); ParameterDesc param = new ParameterDesc(qname, ParameterDesc.IN, typeQName); param.setJavaType(f[j].getType()); exceptionParams.add(param); } } String pkgAndClsName = ex.getName(); FaultDesc fault = new FaultDesc(); fault.setName(pkgAndClsName); fault.setParameters(exceptionParams); operation.addFault(fault); */ FaultDesc fault = operation.getFaultByClass(ex, false); boolean isNew; // If we didn't find one, create a new one if (fault == null) { fault = new FaultDesc(); isNew = true; } else { isNew = false; } // Try to fil in any parts of the faultDesc that aren't there // XMLType QName xmlType = fault.getXmlType(); if (xmlType == null) { fault.setXmlType(getTypeMapping().getTypeQName(ex)); } // Name and Class Name String pkgAndClsName = ex.getName(); if (fault.getClassName() == null) { fault.setClassName(pkgAndClsName); } if (fault.getName() == null) { String name = pkgAndClsName.substring( pkgAndClsName.lastIndexOf('.') + 1, pkgAndClsName.length()); fault.setName(name); } // Parameters // We add a single parameter which points to the type if (fault.getParameters() == null) { if (xmlType == null) { xmlType = getTypeMapping().getTypeQName(ex); } QName qname = fault.getQName(); if (qname == null) { qname = new QName("", "fault"); } ParameterDesc param = new ParameterDesc( qname, ParameterDesc.IN, xmlType); param.setJavaType(ex); ArrayList exceptionParams = new ArrayList(); exceptionParams.add(param); fault.setParameters(exceptionParams); } // QName if (fault.getQName() == null) { fault.setQName(new QName(pkgAndClsName)); } if (isNew) { // Add the fault to the operation operation.addFault(fault); } } } } private String[] getParamNames(Method method) { synchronized (method2ParamsMap) { String [] paramNames = (String []) method2ParamsMap.get(method); if(paramNames != null) return paramNames; paramNames = ParamNameExtractor.getParameterNamesFromDebugInfo(method); method2ParamsMap.put(method, paramNames); return paramNames; } } public void setNamespaceMappings(List namespaces) { namespaceMappings = namespaces; } public String getDefaultNamespace() { if (namespaceMappings == null || namespaceMappings.isEmpty()) return null; return (String)namespaceMappings.get(0); } public void setDefaultNamespace(String namespace) { if (namespaceMappings == null) namespaceMappings = new ArrayList(); namespaceMappings.add(0, namespace); } public void setProperty(String name, Object value) { if (properties == null) { properties = new HashMap(); } properties.put(name, value); } public Object getProperty(String name) { if (properties == null) return null; return properties.get(name); } public String getEndpointURL() { return endpointURL; } public void setEndpointURL(String endpointURL) { this.endpointURL = endpointURL; } public TypeMappingRegistry getTypeMappingRegistry() { if (tmr == null) { tmr = new TypeMappingRegistryImpl(false); } return tmr; } public void setTypeMappingRegistry(TypeMappingRegistry tmr) { this.tmr = tmr; } public boolean isInitialized() { return implClass != null; } }
7,678
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/ParameterDesc.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.description; import org.apache.axis.utils.Messages; import org.apache.axis.wsdl.symbolTable.TypeEntry; import javax.xml.namespace.QName; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * A Parameter descriptor, collecting the interesting info about an * operation parameter. * * (mostly taken from org.apache.axis.wsdl.toJava.Parameter right now) * * @author Glen Daniels (gdaniels@apache.org) */ public class ParameterDesc implements Serializable { // constant values for the parameter mode. public static final byte IN = 1; public static final byte OUT = 2; public static final byte INOUT = 3; /** The Parameter's XML QName */ private transient QName name; /** A TypeEntry corresponding to this parameter */ public TypeEntry typeEntry; /** The Parameter mode (in, out, inout) */ private byte mode = IN; /** The XML type of this parameter */ private QName typeQName; /** The Java type of this parameter */ private Class javaType = null; /** The order of this parameter (-1 indicates unordered) */ private int order = -1; /** Indicates if this ParameterDesc represents a return or normal parameter **/ private boolean isReturn = false; /** MIME type for this parameter, if there is one */ private String mimeType = null; /** If this ParamDesc represents a literal array, this QName will * determine if it gets written as a "bare" or a "wrapped" schema. */ private QName itemQName; private QName itemType; /** Indicates whether input/output values are stored in the header */ private boolean inHeader = false; private boolean outHeader = false; /** The documentation for the parameter */ private String documentation = null; /** Indicates whether this parameter may be omitted or not (i.e., it has minOccurs="0") */ private boolean omittable = false; /** Indicates whether this parameter is nillable */ private boolean nillable = false; public ParameterDesc() { } /** * Constructor-copy * * @param copy the copy */ public ParameterDesc(ParameterDesc copy) { name = copy.name; typeEntry = copy.typeEntry; mode = copy.mode; typeQName = copy.typeQName; javaType = copy.javaType; order = copy.order; isReturn = copy.isReturn; mimeType = copy.mimeType; inHeader = copy.inHeader; outHeader = copy.outHeader; } /** * Constructor * * @param name the parameter's fully qualified XML name * @param mode IN, OUT, INOUT * @param typeQName the parameter's XML type QName */ public ParameterDesc(QName name, byte mode, QName typeQName) { this.name = name; this.mode = mode; this.typeQName = typeQName; } /** * "Complete" constructor, suitable for usage in skeleton code * * @param name the parameter's fully qualified XML name * @param mode IN, OUT, INOUT * @param typeQName the parameter's XML type QName * @param javaType the parameter's javaType * @param inHeader does this parameter go into the input message header? * @param outHeader does this parameter go into the output message header? */ public ParameterDesc(QName name, byte mode, QName typeQName, Class javaType, boolean inHeader, boolean outHeader) { this(name,mode,typeQName); this.javaType = javaType; this.inHeader = inHeader; this.outHeader = outHeader; } /** * @deprecated * @param name the parameter's fully qualified XML name * @param mode IN, OUT, INOUT * @param typeQName the parameter's XML type QName * @param javaType the parameter's javaType */ public ParameterDesc(QName name, byte mode, QName typeQName, Class javaType) { this(name,mode,typeQName,javaType,false,false); } public String toString() { return toString(""); } public String toString(String indent) { String text=""; text+=indent + "name: " + name + "\n"; text+=indent + "typeEntry: " + typeEntry + "\n"; text+=indent + "mode: " + (mode == IN ? "IN" : mode == INOUT ? "INOUT" : "OUT") + "\n"; text+=indent + "position: " + order + "\n"; text+=indent + "isReturn: " + isReturn + "\n"; text+=indent + "typeQName: " + typeQName + "\n"; text+=indent + "javaType: " + javaType + "\n"; text+=indent + "inHeader: " + inHeader + "\n"; text+=indent + "outHeader: " + outHeader+ "\n"; return text; } // toString /** * Get a mode constant from a string. Defaults to IN, and returns * OUT or INOUT if the string matches (ignoring case). */ public static byte modeFromString(String modeStr) { byte ret = IN; if (modeStr == null) { return IN; } else if (modeStr.equalsIgnoreCase("out")) { ret = OUT; } else if (modeStr.equalsIgnoreCase("inout")) { ret = INOUT; } return ret; } public static String getModeAsString(byte mode) { if (mode == INOUT) { return "inout"; } else if (mode == OUT) { return "out"; } else if (mode == IN) { return "in"; } throw new IllegalArgumentException( Messages.getMessage("badParameterMode", Byte.toString(mode))); } public QName getQName() { return name; } public String getName() { if (name == null) { return null; } else { return name.getLocalPart(); } } public void setName(String name) { this.name = new QName("", name); } public void setQName(QName name) { this.name = name; } public QName getTypeQName() { return typeQName; } public void setTypeQName(QName typeQName) { this.typeQName = typeQName; } /** * Get the java type (note that this is javaType in the signature.) * @return Class javaType */ public Class getJavaType() { return javaType; } /** * Set the java type (note that this is javaType in the signature.) */ public void setJavaType(Class javaType) { // The javaType must match the mode. A Holder is expected for OUT/INOUT // parameters that don't represent the return type. if (javaType != null) { if ((mode == IN || isReturn) && javax.xml.rpc.holders.Holder.class.isAssignableFrom(javaType) || mode != IN && !isReturn && !javax.xml.rpc.holders.Holder.class.isAssignableFrom(javaType)) { throw new IllegalArgumentException( Messages.getMessage("setJavaTypeErr00", javaType.getName(), getModeAsString(mode))); } } this.javaType = javaType; } public byte getMode() { return mode; } public void setMode(byte mode) { this.mode = mode; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public void setInHeader(boolean value) { this.inHeader = value; } public boolean isInHeader() { return this.inHeader; } public void setOutHeader(boolean value) { this.outHeader = value; } public boolean isOutHeader() { return this.outHeader; } /** * Indicates ParameterDesc represents return of OperationDesc * @return true if return parameter of OperationDesc */ public boolean getIsReturn() { return isReturn; } /** * Set to true to indicate return parameter of OperationDesc * @param value boolean that indicates if return parameter of OperationDesc */ public void setIsReturn(boolean value) { isReturn = value; } /** * get the documentation for the parameter */ public String getDocumentation() { return documentation; } /** * set the documentation for the parameter */ public void setDocumentation(String documentation) { this.documentation = documentation; } private void writeObject(ObjectOutputStream out) throws IOException { if (name == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeObject(name.getNamespaceURI()); out.writeObject(name.getLocalPart()); } if (typeQName == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeObject(typeQName.getNamespaceURI()); out.writeObject(typeQName.getLocalPart()); } out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { name = new QName((String)in.readObject(), (String)in.readObject()); } else { name = null; } if (in.readBoolean()) { typeQName = new QName((String)in.readObject(), (String)in.readObject()); } else { typeQName = null; } in.defaultReadObject(); } public QName getItemQName() { return itemQName; } public void setItemQName(QName itemQName) { this.itemQName = itemQName; } public QName getItemType() { return itemType; } public void setItemType(QName itemType) { this.itemType = itemType; } /** * Indicates if this parameter is omittable or not (i.e., if it * has a minimum occurrence of 0). * @return true iff the parameter may be omitted in the request */ public boolean isOmittable() { return omittable; } /** * Indicate if this parameter is omittable or not (i.e., if it * has a minimum occurrence of 0). * @param omittable whether the parameter may be omitted or not */ public void setOmittable(boolean omittable) { this.omittable = omittable; } /** * Indicates whether this parameter is nillable or not. * @return whether this parameter is nillable */ public boolean isNillable() { return nillable; } /** * Indicate if this parameter is nillable. * @param nillable true iff this parameter is nillable */ public void setNillable(boolean nillable) { this.nillable = nillable; } }
7,679
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/ElementDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import javax.xml.namespace.QName; import java.io.Serializable; /** * An AttributeDesc is a FieldDesc for an Java field mapping to an * XML element * * @author Glen Daniels (gdaniels@apache.org) * @author Dominik Kacprzak (dominik@opentoolbox.com) */ public class ElementDesc extends FieldDesc implements Serializable { /** The minOccurs value from the schema */ private int minOccurs = 1; /** The maxOccurs value from the schema */ private int maxOccurs = 1; /** The nillable value from the schema. * By default, element cannot be nillable. */ private boolean nillable = false; /** maxOccurs="unbounded" */ private boolean unbounded = false; /** If this is an array, this holds the array type */ private QName arrayType; /** If this is a "wrapped" array, this tells us the inner QName */ private QName itemQName; public ElementDesc() { super(true); } public boolean isMinOccursZero() { return minOccurs == 0; } public int getMinOccurs() { return minOccurs; } public void setMinOccurs(int minOccurs) { this.minOccurs = minOccurs; } public int getMaxOccurs() { return maxOccurs; } public void setMaxOccurs(int maxOccurs) { this.maxOccurs = maxOccurs; } public void setMaxOccursUnbounded(boolean ubnd) { this.unbounded = ubnd; } public boolean isMaxOccursUnbounded() { return unbounded; } /** * Returns value of nillable property. * * @return */ public boolean isNillable() { return nillable; } /** * Sets value of nillable property. Default: <code>false</code>. * * @param nillable */ public void setNillable(boolean nillable) { this.nillable = nillable; } public QName getArrayType() { return arrayType; } public void setArrayType(QName arrayType) { this.arrayType = arrayType; } public QName getItemQName() { return itemQName; } public void setItemQName(QName itemQName) { this.itemQName = itemQName; } }
7,680
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/FieldDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import javax.xml.namespace.QName; import java.io.Serializable; /** * FieldDescs are metadata objects which control the mapping of a given * Java field to/from XML. * * @author Glen Daniels (gdaniels@apache.org) */ public class FieldDesc implements Serializable { /** The name of the Java field in question */ private String fieldName; /** The XML QName this field maps to */ private QName xmlName; /** The XML Type this field maps to/from */ private QName xmlType; /** The Java type of this field */ private Class javaType; /** An indication of whether this should be an element or an attribute */ // Q : should this be a boolean, or just "instanceof ElementDesc", etc. private boolean _isElement = true; /** An indication that minoccurs is zero */ private boolean minOccursIs0 = false; /** * Can't construct the base class directly, must construct either an * ElementDesc or an AttributeDesc. */ protected FieldDesc(boolean isElement) { _isElement = isElement; } /** * Obtain the field name. */ public String getFieldName() { return fieldName; } /** * Set the field name. */ public void setFieldName(String fieldName) { this.fieldName = fieldName; } /** * Obtain the XML QName for this field */ public QName getXmlName() { return xmlName; } /** * Set the XML QName for this field */ public void setXmlName(QName xmlName) { this.xmlName = xmlName; } public Class getJavaType() { return javaType; } public void setJavaType(Class javaType) { this.javaType = javaType; } /** * Returns the XML type (e.g. xsd:string) for this field */ public QName getXmlType() { return xmlType; } /** * Returns the XML type (e.g. xsd:string) for this field */ public void setXmlType(QName xmlType) { this.xmlType = xmlType; } /** * Check if this is an element or an attribute. * * @return true if this is an ElementDesc, or false if an AttributeDesc */ public boolean isElement() { return _isElement; } public boolean isIndexed() { return false; } /** * Check if this field can be omitted. */ public boolean isMinOccursZero() { return minOccursIs0; } /** * * * @param minOccursIs0 * @deprecated this functionality, which is only relevant to ElementDescs, * now lives in ElementDesc and is more flexible (you can set * minOccurs and maxOccurs as you please) */ public void setMinOccursIs0(boolean minOccursIs0) { this.minOccursIs0 = minOccursIs0; } }
7,681
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/description/AttributeDesc.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * 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.axis.description; import javax.xml.namespace.QName; import java.io.Serializable; /** * An AttributeDesc is a FieldDesc for an Java field mapping to an * XML attribute * * @author Glen Daniels (gdaniels@apache.org) */ public class AttributeDesc extends FieldDesc implements Serializable { public AttributeDesc() { super(false); } /** * Set the XML attribute's name, without giving it a namespace. * * This is the most common usage for AttributeDescs. */ public void setAttributeName(String name) { setXmlName(new QName("", name)); } }
7,682
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDFaultFlow.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.w3c.dom.Element; import javax.xml.namespace.QName; /** * */ public class WSDDFaultFlow extends WSDDChain { /** * Default constructor */ public WSDDFaultFlow() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDFaultFlow(Element e) throws WSDDException { super(e); } protected QName getElementName() { return WSDDConstants.QNAME_FAULTFLOW; } }
7,683
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDDeployment.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.AxisEngine; import org.apache.axis.ConfigurationException; import org.apache.axis.Constants; import org.apache.axis.Handler; import org.apache.axis.WSDDEngineConfiguration; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; /** * WSDD deployment element * * @author James Snell * @author Glen Daniels (gdaniels@apache.org) */ public class WSDDDeployment extends WSDDElement implements WSDDTypeMappingContainer, WSDDEngineConfiguration { protected static Log log = LogFactory.getLog(WSDDDeployment.class.getName()); private HashMap handlers = new HashMap(); private HashMap services = new HashMap(); private HashMap transports = new HashMap(); private HashMap typeMappings = new HashMap(); private WSDDGlobalConfiguration globalConfig = null; /** * Mapping of namespaces -&gt; services */ private HashMap namespaceToServices = new HashMap(); private AxisEngine engine; protected void addHandler(WSDDHandler handler) { handlers.put(handler.getQName(), handler); } protected void addService(WSDDService service) { WSDDService oldService = (WSDDService) services.get(service.getQName()); if (oldService != null) { oldService.removeNamespaceMappings(this); } services.put(service.getQName(), service); } protected void addTransport(WSDDTransport transport) { transports.put(transport.getQName(), transport); } /** * Put a WSDDHandler into this deployment, replacing any other * WSDDHandler which might already be present with the same QName. * * @param handler a WSDDHandler to insert in this deployment */ public void deployHandler(WSDDHandler handler) { handler.deployToRegistry(this); } /** * Put a WSDDTransport into this deployment, replacing any other * WSDDTransport which might already be present with the same QName. * * @param transport a WSDDTransport to insert in this deployment */ public void deployTransport(WSDDTransport transport) { transport.deployToRegistry(this); } /** * Put a WSDDService into this deployment, replacing any other * WSDDService which might already be present with the same QName. * * @param service a WSDDHandler to insert in this deployment */ public void deployService(WSDDService service) { service.deployToRegistry(this); } /** * Remove a named handler * * @param qname the QName of the handler to remove */ public void undeployHandler(QName qname) { handlers.remove(qname); } /** * Remove a named service * * @param qname the QName of the service to remove */ public void undeployService(QName qname) { WSDDService service = (WSDDService) services.get(qname); if (service != null) { service.removeNamespaceMappings(this); services.remove(qname); } } /** * Remove a named transport * * @param qname the QName of the transport to remove */ public void undeployTransport(QName qname) { transports.remove(qname); } public void deployTypeMapping(WSDDTypeMapping typeMapping) throws WSDDException { QName qname = typeMapping.getQName(); String encoding = typeMapping.getEncodingStyle(); // We have to include the encoding in the key // because otherwise we would overwrite exiting mappings typeMappings.put(qname + encoding, typeMapping); if (tmrDeployed) deployMapping(typeMapping); } /** * Default constructor */ public WSDDDeployment() { } /** * Create an element in WSDD that wraps an extant DOM element * * @param e the element to create the deployment from * @throws WSDDException when problems occur deploying a service or type mapping. */ public WSDDDeployment(Element e) throws WSDDException { super(e); Element [] elements = getChildElements(e, ELEM_WSDD_HANDLER); int i; for (i = 0; i < elements.length; i++) { WSDDHandler handler = new WSDDHandler(elements[i]); deployHandler(handler); } elements = getChildElements(e, ELEM_WSDD_CHAIN); for (i = 0; i < elements.length; i++) { WSDDChain chain = new WSDDChain(elements[i]); deployHandler(chain); } elements = getChildElements(e, ELEM_WSDD_TRANSPORT); for (i = 0; i < elements.length; i++) { WSDDTransport transport = new WSDDTransport(elements[i]); deployTransport(transport); } elements = getChildElements(e, ELEM_WSDD_SERVICE); for (i = 0; i < elements.length; i++) { try { WSDDService service = new WSDDService(elements[i]); deployService(service); } catch (WSDDNonFatalException ex) { // If it's non-fatal, just keep on going log.info(Messages.getMessage("ignoringNonFatalException00"), ex); } catch (WSDDException ex) { // otherwise throw it upwards throw ex; } } elements = getChildElements(e, ELEM_WSDD_TYPEMAPPING); for (i = 0; i < elements.length; i++) { try { WSDDTypeMapping mapping = new WSDDTypeMapping(elements[i]); deployTypeMapping(mapping); } catch (WSDDNonFatalException ex) { // If it's non-fatal, just keep on going log.info(Messages.getMessage("ignoringNonFatalException00"), ex); } catch (WSDDException ex) { // otherwise throw it upwards throw ex; } } elements = getChildElements(e, ELEM_WSDD_BEANMAPPING); for (i = 0; i < elements.length; i++) { WSDDBeanMapping mapping = new WSDDBeanMapping(elements[i]); deployTypeMapping(mapping); } elements = getChildElements(e, ELEM_WSDD_ARRAYMAPPING); for (i = 0; i < elements.length; i++) { WSDDArrayMapping mapping = new WSDDArrayMapping(elements[i]); deployTypeMapping(mapping); } Element el = getChildElement(e, ELEM_WSDD_GLOBAL); if (el != null) globalConfig = new WSDDGlobalConfiguration(el); } protected QName getElementName() { return QNAME_DEPLOY; } public void deployToRegistry(WSDDDeployment target) throws ConfigurationException { WSDDGlobalConfiguration global = getGlobalConfiguration(); if (global != null) { target.setGlobalConfiguration(global); } Iterator i = handlers.values().iterator(); while (i.hasNext()) { WSDDHandler handler = (WSDDHandler) i.next(); target.deployHandler(handler); } i = transports.values().iterator(); while (i.hasNext()) { WSDDTransport transport = (WSDDTransport) i.next(); target.deployTransport(transport); } i = services.values().iterator(); while (i.hasNext()) { WSDDService service = (WSDDService) i.next(); service.deployToRegistry(target); } i = typeMappings.values().iterator(); while (i.hasNext()) { WSDDTypeMapping mapping = (WSDDTypeMapping) i.next(); target.deployTypeMapping(mapping); } } private void deployMapping(WSDDTypeMapping mapping) throws WSDDException { String encodingStyle = mapping.getEncodingStyle(); if (encodingStyle == null) { encodingStyle = Constants.URI_DEFAULT_SOAP_ENC; } mapping.registerTo(tmr.getOrMakeTypeMapping(encodingStyle)); } public void writeToContext(SerializationContext context) throws IOException { context.registerPrefixForURI(NS_PREFIX_WSDD, URI_WSDD); context.registerPrefixForURI(NS_PREFIX_WSDD_JAVA, URI_WSDD_JAVA); context.startElement(QNAME_DEPLOY, null); if (globalConfig != null) { globalConfig.writeToContext(context); } Iterator i = handlers.values().iterator(); while (i.hasNext()) { WSDDHandler handler = (WSDDHandler) i.next(); handler.writeToContext(context); } i = services.values().iterator(); while (i.hasNext()) { WSDDService service = (WSDDService) i.next(); service.writeToContext(context); } i = transports.values().iterator(); while (i.hasNext()) { WSDDTransport transport = (WSDDTransport) i.next(); transport.writeToContext(context); } i = typeMappings.values().iterator(); while (i.hasNext()) { WSDDTypeMapping mapping = (WSDDTypeMapping) i.next(); mapping.writeToContext(context); } context.endElement(); } /** * Get our global configuration * * @return a global configuration object */ public WSDDGlobalConfiguration getGlobalConfiguration() { return globalConfig; } public void setGlobalConfiguration(WSDDGlobalConfiguration globalConfig) { this.globalConfig = globalConfig; } /** * @return an array of type mappings in this deployment */ public WSDDTypeMapping[] getTypeMappings() { WSDDTypeMapping[] t = new WSDDTypeMapping[typeMappings.size()]; typeMappings.values().toArray(t); return t; } /** * Return an array of the services in this deployment */ public WSDDService[] getServices() { WSDDService [] serviceArray = new WSDDService[services.size()]; services.values().toArray(serviceArray); return serviceArray; } /** * Return the WSDD description for a given named service */ public WSDDService getWSDDService(QName qname) { return (WSDDService) services.get(qname); } /** * Return an instance of the named handler. * * @param name the name of the handler to get * @return an Axis handler with the specified QName or null of not found */ public Handler getHandler(QName name) throws ConfigurationException { WSDDHandler h = (WSDDHandler) handlers.get(name); if (h != null) { return h.getInstance(this); } return null; } /** * Retrieve an instance of the named transport. * * @param name the <code>QName</code> of the transport * @return a <code>Handler</code> implementing the transport * @throws ConfigurationException if there was an error resolving the * transport */ public Handler getTransport(QName name) throws ConfigurationException { WSDDTransport t = (WSDDTransport) transports.get(name); if (t != null) { return t.getInstance(this); } return null; } /** * Retrieve an instance of the named service. * * @param name the <code>QName</code> identifying the * <code>Service</code> * @return the <code>Service</code> associated with <code>qname</code> * @throws ConfigurationException if there was an error resolving the * qname */ public SOAPService getService(QName name) throws ConfigurationException { WSDDService s = (WSDDService) services.get(name); if (s != null) { return (SOAPService) s.getInstance(this); } return null; } public SOAPService getServiceByNamespaceURI(String namespace) throws ConfigurationException { WSDDService s = (WSDDService) namespaceToServices.get(namespace); if (s != null) { return (SOAPService) s.getInstance(this); } return null; } public void configureEngine(AxisEngine engine) throws ConfigurationException { this.engine = engine; } public void writeEngineConfig(AxisEngine engine) throws ConfigurationException { } TypeMappingRegistry tmr = new TypeMappingRegistryImpl(); public TypeMapping getTypeMapping(String encodingStyle) throws ConfigurationException { return (TypeMapping) getTypeMappingRegistry().getTypeMapping(encodingStyle); } private boolean tmrDeployed = false; public TypeMappingRegistry getTypeMappingRegistry() throws ConfigurationException { if (false == tmrDeployed) { Iterator i = typeMappings.values().iterator(); while (i.hasNext()) { WSDDTypeMapping mapping = (WSDDTypeMapping) i.next(); deployMapping(mapping); } tmrDeployed = true; } return tmr; } public Handler getGlobalRequest() throws ConfigurationException { if (globalConfig != null) { WSDDRequestFlow reqFlow = globalConfig.getRequestFlow(); if (reqFlow != null) return reqFlow.getInstance(this); } return null; } public Handler getGlobalResponse() throws ConfigurationException { if (globalConfig != null) { WSDDResponseFlow respFlow = globalConfig.getResponseFlow(); if (respFlow != null) return respFlow.getInstance(this); } return null; } public Hashtable getGlobalOptions() throws ConfigurationException { return globalConfig.getParametersTable(); } public List getRoles() { return globalConfig == null ? new ArrayList() : globalConfig.getRoles(); } /** * Get an enumeration of the services deployed to this engine */ public Iterator getDeployedServices() throws ConfigurationException { ArrayList serviceDescs = new ArrayList(); for (Iterator i = services.values().iterator(); i.hasNext();) { WSDDService service = (WSDDService) i.next(); try { service.makeNewInstance(this); serviceDescs.add(service.getServiceDesc()); } catch (WSDDNonFatalException ex) { // If it's non-fatal, just keep on going log.info(Messages.getMessage("ignoringNonFatalException00"), ex); } } return serviceDescs.iterator(); } /** * Register a particular namepsace which maps to a given WSDDService. * This will be used for namespace-based dispatching. * * @param namespace a namespace URI * @param service the target WSDDService */ public void registerNamespaceForService(String namespace, WSDDService service) { namespaceToServices.put(namespace, service); } /** * Remove a namespace -&gt; WSDDService mapping. * * @param namespace the namespace URI to unmap */ public void removeNamespaceMapping(String namespace) { namespaceToServices.remove(namespace); } public AxisEngine getEngine() { return engine; } public WSDDDeployment getDeployment() { return this; } public WSDDHandler[] getHandlers() { WSDDHandler [] handlerArray = new WSDDHandler[handlers.size()]; handlers.values().toArray(handlerArray); return handlerArray; } public WSDDHandler getWSDDHandler(QName qname) { return (WSDDHandler) handlers.get(qname); } public WSDDTransport[] getTransports() { WSDDTransport [] transportArray = new WSDDTransport[transports.size()]; transports.values().toArray(transportArray); return transportArray; } public WSDDTransport getWSDDTransport(QName qname) { return (WSDDTransport) transports.get(qname); } }
7,684
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDRequestFlow.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.w3c.dom.Element; import javax.xml.namespace.QName; /** * */ public class WSDDRequestFlow extends WSDDChain { /** * Default constructor */ public WSDDRequestFlow() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDRequestFlow(Element e) throws WSDDException { super(e); } protected QName getElementName() { return WSDDConstants.QNAME_REQFLOW; } }
7,685
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDUndeployment.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Iterator; import java.util.Vector; /** * WSDD deployment element * * @author James Snell */ public class WSDDUndeployment extends WSDDElement implements WSDDTypeMappingContainer { private Vector handlers = new Vector(); private Vector chains = new Vector(); private Vector services = new Vector(); private Vector transports = new Vector(); private Vector typeMappings = new Vector(); public void addHandler(QName handler) { handlers.add(handler); } public void addChain(QName chain) { chains.add(chain); } public void addTransport(QName transport) { transports.add(transport); } public void addService(QName service) { services.add(service); } public void deployTypeMapping(WSDDTypeMapping typeMapping) throws WSDDException { typeMappings.add(typeMapping); } /** * Default constructor */ public WSDDUndeployment() { } private QName getQName(Element el) throws WSDDException { String attr = el.getAttribute(ATTR_NAME); if (attr == null || "".equals(attr)) throw new WSDDException(Messages.getMessage("badNameAttr00")); return new QName("", attr); } /** * Constructor - build an undeployment from a DOM Element. * * @param e the DOM Element to initialize from * @throws WSDDException if there is a problem */ public WSDDUndeployment(Element e) throws WSDDException { super(e); Element [] elements = getChildElements(e, ELEM_WSDD_HANDLER); int i; for (i = 0; i < elements.length; i++) { addHandler(getQName(elements[i])); } elements = getChildElements(e, ELEM_WSDD_CHAIN); for (i = 0; i < elements.length; i++) { addChain(getQName(elements[i])); } elements = getChildElements(e, ELEM_WSDD_TRANSPORT); for (i = 0; i < elements.length; i++) { addTransport(getQName(elements[i])); } elements = getChildElements(e, ELEM_WSDD_SERVICE); for (i = 0; i < elements.length; i++) { addService(getQName(elements[i])); } /* // How to deal with undeploying mappings? elements = getChildElements(e, ELEM_WSDD_TYPEMAPPING); for (i = 0; i < elements.length; i++) { WSDDTypeMapping mapping = new WSDDTypeMapping(elements[i]); addTypeMapping(mapping); } elements = getChildElements(e, ELEM_WSDD_BEANMAPPING); for (i = 0; i < elements.length; i++) { WSDDBeanMapping mapping = new WSDDBeanMapping(elements[i]); addTypeMapping(mapping); } */ } protected QName getElementName() { return QNAME_UNDEPLOY; } public void undeployFromRegistry(WSDDDeployment registry) throws ConfigurationException { QName qname; for (int n = 0; n < handlers.size(); n++) { qname = (QName)handlers.get(n); registry.undeployHandler(qname); } for (int n = 0; n < chains.size(); n++) { qname = (QName)chains.get(n); registry.undeployHandler(qname); } for (int n = 0; n < transports.size(); n++) { qname = (QName)transports.get(n); registry.undeployTransport(qname); } for (int n = 0; n < services.size(); n++) { qname = (QName)services.get(n); registry.undeployService(qname); } } private void writeElement(SerializationContext context, QName elementQName, QName qname) throws IOException { AttributesImpl attrs = new org.xml.sax.helpers.AttributesImpl(); attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", context.qName2String(qname)); context.startElement(elementQName, attrs); context.endElement(); } public void writeToContext(SerializationContext context) throws IOException { context.registerPrefixForURI(NS_PREFIX_WSDD, URI_WSDD); context.startElement(WSDDConstants.QNAME_UNDEPLOY, null); Iterator i = handlers.iterator(); QName qname; while (i.hasNext()) { qname = (QName)i.next(); writeElement(context, QNAME_HANDLER, qname); } i = chains.iterator(); while (i.hasNext()) { qname = (QName)i.next(); writeElement(context, QNAME_CHAIN, qname); } i = services.iterator(); while (i.hasNext()) { qname = (QName)i.next(); writeElement(context, QNAME_SERVICE, qname); } i = transports.iterator(); while (i.hasNext()) { qname = (QName)i.next(); writeElement(context, QNAME_TRANSPORT, qname); } i = typeMappings.iterator(); while (i.hasNext()) { WSDDTypeMapping mapping = (WSDDTypeMapping)i.next(); mapping.writeToContext(context); } context.endElement(); } /** * * @return XXX */ public WSDDTypeMapping[] getTypeMappings() { WSDDTypeMapping[] t = new WSDDTypeMapping[typeMappings.size()]; typeMappings.toArray(t); return t; } }
7,686
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDGlobalConfiguration.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.io.IOException; import java.util.List; import java.util.ArrayList; /** * Represents the global configuration of the Axis engine. * * @author James Snell */ public class WSDDGlobalConfiguration extends WSDDDeployableItem { private WSDDRequestFlow requestFlow; private WSDDResponseFlow responseFlow; private ArrayList roles = new ArrayList(); /** * Default constructor */ public WSDDGlobalConfiguration() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDGlobalConfiguration(Element e) throws WSDDException { super(e); Element reqEl = getChildElement(e, ELEM_WSDD_REQFLOW); if (reqEl != null && reqEl.getElementsByTagName("*").getLength()>0) { requestFlow = new WSDDRequestFlow(reqEl); } Element respEl = getChildElement(e, ELEM_WSDD_RESPFLOW); if (respEl != null && respEl.getElementsByTagName("*").getLength()>0) { responseFlow = new WSDDResponseFlow(respEl); } Element [] roleElements = getChildElements(e, ELEM_WSDD_ROLE); for (int i = 0; i < roleElements.length; i++) { String role = XMLUtils.getChildCharacterData(roleElements[i]); roles.add(role); } } protected QName getElementName() { return WSDDConstants.QNAME_GLOBAL; } /** * Get our request flow */ public WSDDRequestFlow getRequestFlow() { return requestFlow; } /** * Set our request flow */ public void setRequestFlow(WSDDRequestFlow reqFlow) { requestFlow = reqFlow; } /** * Get our response flow */ public WSDDResponseFlow getResponseFlow() { return responseFlow; } /** * Set the response flow */ public void setResponseFlow(WSDDResponseFlow responseFlow) { this.responseFlow = responseFlow; } /** * * @return XXX */ public WSDDFaultFlow[] getFaultFlows() { return null; } /** * * @param name XXX * @return XXX */ public WSDDFaultFlow getFaultFlow(QName name) { WSDDFaultFlow[] t = getFaultFlows(); for (int n = 0; n < t.length; n++) { if (t[n].getQName().equals(name)) { return t[n]; } } return null; } /** * * @return XXX */ public QName getType() { return null; } /** * * @param type XXX */ public void setType(String type) throws WSDDException { throw new WSDDException(Messages.getMessage("noTypeOnGlobalConfig00")); } /** * * @param registry XXX * @return XXX */ public Handler makeNewInstance(EngineConfiguration registry) { return null; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { context.startElement(QNAME_GLOBAL, null); writeParamsToContext(context); if (requestFlow != null) requestFlow.writeToContext(context); if (responseFlow != null) responseFlow.writeToContext(context); context.endElement(); } public void deployToRegistry(WSDDDeployment registry) throws ConfigurationException { if (requestFlow != null) requestFlow.deployToRegistry(registry); if (responseFlow != null) responseFlow.deployToRegistry(registry); } public List getRoles() { return (List)roles.clone(); } }
7,687
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDJAXRPCHandlerInfoChain.java
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.handlers.HandlerInfoChainFactory; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import javax.xml.rpc.handler.HandlerInfo; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * */ public class WSDDJAXRPCHandlerInfoChain extends WSDDHandler { protected static Log log = LogFactory.getLog(WSDDJAXRPCHandlerInfoChain.class.getName()); private ArrayList _hiList; private HandlerInfoChainFactory _hiChainFactory; private String[] _roles; /** * Default constructor */ public WSDDJAXRPCHandlerInfoChain() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDJAXRPCHandlerInfoChain(Element e) throws WSDDException { super(e); ArrayList infoList = new ArrayList(); _hiList = new ArrayList(); Element[] elements = getChildElements(e, ELEM_WSDD_JAXRPC_HANDLERINFO); if (elements.length != 0) { for (int i = 0; i < elements.length; i++) { WSDDJAXRPCHandlerInfo handlerInfo = new WSDDJAXRPCHandlerInfo(elements[i]); _hiList.add(handlerInfo); String handlerClassName = handlerInfo.getHandlerClassName(); Class handlerClass = null; try { handlerClass = ClassUtils.forName(handlerClassName); } catch (ClassNotFoundException cnf) { log.error(Messages.getMessage("handlerInfoChainNoClass00", handlerClassName), cnf); } Map handlerMap = handlerInfo.getHandlerMap(); QName[] headers = handlerInfo.getHeaders(); if (handlerClass != null) { HandlerInfo hi = new HandlerInfo(handlerClass, handlerMap, headers); infoList.add(hi); } } } _hiChainFactory = new HandlerInfoChainFactory(infoList); elements = getChildElements(e, ELEM_WSDD_JAXRPC_ROLE); if (elements.length != 0) { ArrayList roleList = new ArrayList(); for (int i = 0; i < elements.length; i++) { String role = elements[i].getAttribute( ATTR_SOAPACTORNAME); roleList.add(role); } _roles =new String[roleList.size()]; _roles = (String[]) roleList.toArray(_roles); _hiChainFactory.setRoles(_roles); } } public HandlerInfoChainFactory getHandlerChainFactory() { return _hiChainFactory; } public void setHandlerChainFactory(HandlerInfoChainFactory handlerInfoChainFactory) { _hiChainFactory = handlerInfoChainFactory; } protected QName getElementName() { return WSDDConstants.QNAME_JAXRPC_HANDLERINFOCHAIN; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { context.startElement(QNAME_JAXRPC_HANDLERINFOCHAIN,null); List his = _hiList; Iterator iter = his.iterator(); while (iter.hasNext()) { WSDDJAXRPCHandlerInfo hi = (WSDDJAXRPCHandlerInfo) iter.next(); hi.writeToContext(context); } if (_roles != null) { for (int i=0; i < _roles.length ; i++) { AttributesImpl attrs1 = new AttributesImpl(); attrs1.addAttribute("", ATTR_SOAPACTORNAME, ATTR_SOAPACTORNAME, "CDATA", _roles[i]); context.startElement(QNAME_JAXRPC_ROLE,attrs1); context.endElement(); } } context.endElement(); } public ArrayList getHandlerInfoList() { return _hiList; } public void setHandlerInfoList(ArrayList hiList) { _hiList = hiList; } public String[] getRoles() { return _roles; } public void setRoles(String[] roles) { _roles = roles; } }
7,688
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDService.java
/* * Copyright 2001-2005 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; import org.apache.axis.ConfigurationException; import org.apache.axis.Constants; import org.apache.axis.EngineConfiguration; import org.apache.axis.FaultableHandler; import org.apache.axis.Handler; import org.apache.axis.MessageContext; import org.apache.axis.attachments.Attachments; import org.apache.axis.attachments.AttachmentsImpl; import org.apache.axis.constants.Style; import org.apache.axis.constants.Use; import org.apache.axis.description.JavaServiceDesc; import org.apache.axis.description.ServiceDesc; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.encoding.TypeMappingRegistry; import org.apache.axis.encoding.TypeMappingRegistryImpl; import org.apache.axis.handlers.HandlerInfoChainFactory; import org.apache.axis.handlers.soap.SOAPService; import org.apache.axis.providers.java.JavaProvider; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; /** * A service represented in WSDD. * * @author Glen Daniels (gdaniels@apache.org) */ public class WSDDService extends WSDDTargetedChain implements WSDDTypeMappingContainer { private TypeMappingRegistry tmr = null; private Vector faultFlows = new Vector(); private Vector typeMappings = new Vector(); private Vector operations = new Vector(); /** Which namespaces should auto-dispatch to this service? */ private Vector namespaces = new Vector(); /** Which roles does this service support? */ private List roles = new ArrayList(); private String descriptionURL; /** Style - document, wrapped, message, or RPC (the default) */ private Style style = Style.DEFAULT; /** Use - encoded (the default) or literal */ private Use use = Use.DEFAULT; private transient SOAPService cachedService = null; /** * Our provider - used to figure out which Handler we use as a service * pivot (see getInstance() below) */ private QName providerQName; // private HandlerInfoChainFactory _hiChainFactory; private WSDDJAXRPCHandlerInfoChain _wsddHIchain; JavaServiceDesc desc = new JavaServiceDesc(); /** * Is streaming (i.e. NO high-fidelity recording, deserialize on the fly) * on for this service? */ private boolean streaming = false; /** * What attachment format should be used? */ private int sendType = Attachments.SEND_TYPE_NOTSET; /** * Default constructor */ public WSDDService() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDService(Element e) throws WSDDException { super(e); desc.setName(getQName().getLocalPart()); String styleStr = e.getAttribute(ATTR_STYLE); if (styleStr != null && !styleStr.equals("")) { style = Style.getStyle(styleStr, Style.DEFAULT); desc.setStyle(style); providerQName = style.getProvider(); } String useStr = e.getAttribute(ATTR_USE); if (useStr != null && !useStr.equals("")) { use = Use.getUse(useStr, Use.DEFAULT); desc.setUse(use); } else { if (style != Style.RPC) { // Default to use=literal if not style=RPC use = Use.LITERAL; desc.setUse(use); } } String streamStr = e.getAttribute(ATTR_STREAMING); if (streamStr != null && streamStr.equals("on")) { streaming = true; } String attachmentStr = e.getAttribute(ATTR_ATTACHMENT_FORMAT); if (attachmentStr != null && !attachmentStr.equals("")) { sendType = AttachmentsImpl.getSendType(attachmentStr); } Element [] operationElements = getChildElements(e, ELEM_WSDD_OPERATION); for (int i = 0; i < operationElements.length; i++) { WSDDOperation operation = new WSDDOperation(operationElements[i], desc); addOperation(operation); } Element [] typeMappingElements = getChildElements(e, ELEM_WSDD_TYPEMAPPING); for (int i = 0; i < typeMappingElements.length; i++) { WSDDTypeMapping mapping = new WSDDTypeMapping(typeMappingElements[i]); typeMappings.add(mapping); } Element [] beanMappingElements = getChildElements(e, ELEM_WSDD_BEANMAPPING); for (int i = 0; i < beanMappingElements.length; i++) { WSDDBeanMapping mapping = new WSDDBeanMapping(beanMappingElements[i]); typeMappings.add(mapping); } Element [] arrayMappingElements = getChildElements(e, ELEM_WSDD_ARRAYMAPPING); for (int i = 0; i < arrayMappingElements.length; i++) { WSDDArrayMapping mapping = new WSDDArrayMapping(arrayMappingElements[i]); typeMappings.add(mapping); } Element [] namespaceElements = getChildElements(e, ELEM_WSDD_NAMESPACE); for (int i = 0; i < namespaceElements.length; i++) { // Register a namespace for this service String ns = XMLUtils.getChildCharacterData(namespaceElements[i]); namespaces.add(ns); } if (!namespaces.isEmpty()) desc.setNamespaceMappings(namespaces); Element [] roleElements = getChildElements(e, ELEM_WSDD_ROLE); for (int i = 0; i < roleElements.length; i++) { String role = XMLUtils.getChildCharacterData(roleElements[i]); roles.add(role); } Element wsdlElem = getChildElement(e, ELEM_WSDD_WSDLFILE); if (wsdlElem != null) { String fileName = XMLUtils.getChildCharacterData(wsdlElem); desc.setWSDLFile(fileName.trim()); } Element docElem = getChildElement(e, ELEM_WSDD_DOC); if (docElem != null) { WSDDDocumentation documentation = new WSDDDocumentation(docElem); desc.setDocumentation(documentation.getValue()); } Element urlElem = getChildElement(e, ELEM_WSDD_ENDPOINTURL); if (urlElem != null) { String endpointURL = XMLUtils.getChildCharacterData(urlElem); desc.setEndpointURL(endpointURL); } String providerStr = e.getAttribute(ATTR_PROVIDER); if (providerStr != null && !providerStr.equals("")) { providerQName = XMLUtils.getQNameFromString(providerStr, e); if (WSDDConstants.QNAME_JAVAMSG_PROVIDER.equals(providerQName)) { // Message style if message provider... desc.setStyle(Style.MESSAGE); } } // Add in JAX-RPC support for HandlerInfo chains Element hcEl = getChildElement(e, ELEM_WSDD_JAXRPC_CHAIN); if (hcEl != null) { _wsddHIchain = new WSDDJAXRPCHandlerInfoChain(hcEl); } // Initialize TypeMappingRegistry initTMR(); // call to validate standard descriptors for this service validateDescriptors(); } /** * Initialize a TypeMappingRegistry with the * WSDDTypeMappings. * Note: Extensions of WSDDService may override * initTMR to popluate the tmr with different * type mappings. */ protected void initTMR() throws WSDDException { // If not created, construct a tmr // and populate it with the type mappings. if (tmr == null) { createTMR(); for (int i=0; i<typeMappings.size(); i++) { deployTypeMapping((WSDDTypeMapping) typeMappings.get(i)); } } } private void createTMR() { tmr = new TypeMappingRegistryImpl(false); String version = getParameter("typeMappingVersion"); ((TypeMappingRegistryImpl)tmr).doRegisterFromVersion(version); } /** * This method can be used for dynamic deployment using new WSDDService() * etc. It validates some standard parameters for some standard providers * (if present). Do this before deployment.deployService(). */ public void validateDescriptors() throws WSDDException { if (tmr == null) { initTMR(); } desc.setTypeMappingRegistry(tmr); desc.setTypeMapping(getTypeMapping(desc.getUse().getEncoding())); String allowedMethods = getParameter(JavaProvider.OPTION_ALLOWEDMETHODS); if (allowedMethods != null && !"*".equals(allowedMethods)) { ArrayList methodList = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(allowedMethods, " ,"); while (tokenizer.hasMoreTokens()) { methodList.add(tokenizer.nextToken()); } desc.setAllowedMethods(methodList); } } /** * Add a WSDDTypeMapping to the Service. * @param mapping **/ public void addTypeMapping(WSDDTypeMapping mapping) { typeMappings.add(mapping); } /** * Add a WSDDOperation to the Service. * @param operation the operation to add **/ public void addOperation(WSDDOperation operation) { operations.add(operation); desc.addOperationDesc(operation.getOperationDesc()); } protected QName getElementName() { return QNAME_SERVICE; } /** * Get any service description URL which might be associated with this * service. * * @return a String containing a URL, or null. */ public String getServiceDescriptionURL() { return descriptionURL; } /** * Set the service description URL for this service. * * @param sdUrl a String containing a URL */ public void setServiceDescriptionURL(String sdUrl) { descriptionURL = sdUrl; } public QName getProviderQName() { return providerQName; } public void setProviderQName(QName providerQName) { this.providerQName = providerQName; } public ServiceDesc getServiceDesc() { return desc; } /** * Get the service style - document or RPC */ public Style getStyle() { return style; } /** * Set the service style - document or RPC */ public void setStyle(Style style) { this.style = style; } /** * Get the service use - literal or encoded */ public Use getUse() { return use; } /** * Set the service use - literal or encoded */ public void setUse(Use use) { this.use = use; } /** * * @return XXX */ public WSDDFaultFlow[] getFaultFlows() { WSDDFaultFlow[] t = new WSDDFaultFlow[faultFlows.size()]; faultFlows.toArray(t); return t; } /** * Obtain the list of namespaces registered for this service * @return a Vector of namespaces (Strings) which should dispatch to * this service */ public Vector getNamespaces() { return namespaces; } /** * * @param name XXX * @return XXX */ public WSDDFaultFlow getFaultFlow(QName name) { WSDDFaultFlow[] t = getFaultFlows(); for (int n = 0; n < t.length; n++) { if (t[n].getQName().equals(name)) { return t[n]; } } return null; } /** * * @param registry XXX * @return XXX * @throws ConfigurationException XXX */ public Handler makeNewInstance(EngineConfiguration registry) throws ConfigurationException { if (cachedService != null) { return cachedService; } // Make sure tmr is initialized. initTMR(); Handler reqHandler = null; WSDDChain request = getRequestFlow(); if (request != null) { reqHandler = request.getInstance(registry); } Handler providerHandler = null; if (providerQName != null) { try { providerHandler = WSDDProvider.getInstance(providerQName, this, registry); } catch (Exception e) { throw new ConfigurationException(e); } if (providerHandler == null) throw new WSDDException( Messages.getMessage("couldntConstructProvider00")); } Handler respHandler = null; WSDDChain response = getResponseFlow(); if (response != null) { respHandler = response.getInstance(registry); } SOAPService service = new SOAPService(reqHandler, providerHandler, respHandler); service.setStyle(style); service.setUse(use); service.setServiceDescription(desc); service.setHighFidelityRecording(!streaming); service.setSendType(sendType); if ( getQName() != null ) service.setName(getQName().getLocalPart()); service.setOptions(getParametersTable()); service.setRoles(roles); service.setEngine(((WSDDDeployment)registry).getEngine()); if (use != Use.ENCODED) { // If not encoded, turn off multi-refs and prefer // not to sent xsi:type and xsi:nil service.setOption(AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); service.setOption(AxisEngine.PROP_SEND_XSI, Boolean.FALSE); } // Set handlerInfoChain if (_wsddHIchain != null) { HandlerInfoChainFactory hiChainFactory = _wsddHIchain.getHandlerChainFactory(); service.setOption(Constants.ATTR_HANDLERINFOCHAIN, hiChainFactory); } AxisEngine.normaliseOptions(service); WSDDFaultFlow [] faultFlows = getFaultFlows(); if (faultFlows != null && faultFlows.length > 0) { FaultableHandler wrapper = new FaultableHandler(service); for (int i = 0; i < faultFlows.length; i++) { WSDDFaultFlow flow = faultFlows[i]; Handler faultHandler = flow.getInstance(registry); wrapper.setOption("fault-" + flow.getQName().getLocalPart(), faultHandler); } } try { service.getInitializedServiceDesc(MessageContext.getCurrentContext()); } catch (AxisFault axisFault) { throw new ConfigurationException(axisFault); } cachedService = service; return service; } public void deployTypeMapping(WSDDTypeMapping mapping) throws WSDDException { if (!typeMappings.contains(mapping)) { typeMappings.add(mapping); } if (tmr == null) { createTMR(); } // Get the encoding style from the mapping, if it isn't set // use the use of the service to map doc/lit or rpc/enc String encodingStyle = mapping.getEncodingStyle(); if (encodingStyle == null) { encodingStyle = use.getEncoding(); } TypeMapping tm = tmr.getOrMakeTypeMapping(encodingStyle); desc.setTypeMappingRegistry(tmr); desc.setTypeMapping(tm); mapping.registerTo(tm); } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); QName name = getQName(); if (name != null) { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", context.qName2String(name)); } if (providerQName != null) { attrs.addAttribute("", ATTR_PROVIDER, ATTR_PROVIDER, "CDATA", context.qName2String(providerQName)); } if (style != Style.DEFAULT) { attrs.addAttribute("", ATTR_STYLE, ATTR_STYLE, "CDATA", style.getName()); } if (use != Use.DEFAULT) { attrs.addAttribute("", ATTR_USE, ATTR_USE, "CDATA", use.getName()); } if (streaming) { attrs.addAttribute("", ATTR_STREAMING, ATTR_STREAMING, "CDATA", "on"); } if (sendType != Attachments.SEND_TYPE_NOTSET) { attrs.addAttribute("", ATTR_ATTACHMENT_FORMAT, ATTR_ATTACHMENT_FORMAT, "CDATA", AttachmentsImpl.getSendTypeString(sendType)); } context.startElement(WSDDConstants.QNAME_SERVICE, attrs); if (desc.getWSDLFile() != null) { context.startElement(QNAME_WSDLFILE, null); context.writeSafeString(desc.getWSDLFile()); context.endElement(); } if (desc.getDocumentation() != null) { WSDDDocumentation documentation = new WSDDDocumentation(desc.getDocumentation()); documentation.writeToContext(context); } for (int i = 0; i < operations.size(); i++) { WSDDOperation operation = (WSDDOperation) operations.elementAt(i); operation.writeToContext(context); } writeFlowsToContext(context); writeParamsToContext(context); for (int i=0; i < typeMappings.size(); i++) { ((WSDDTypeMapping) typeMappings.elementAt(i)).writeToContext(context); } for (int i=0; i < namespaces.size(); i++ ) { context.startElement(QNAME_NAMESPACE, null); context.writeString((String)namespaces.get(i)); context.endElement(); } String endpointURL = desc.getEndpointURL(); if (endpointURL != null) { context.startElement(QNAME_ENDPOINTURL, null); context.writeSafeString(endpointURL); context.endElement(); } if (_wsddHIchain != null) { _wsddHIchain.writeToContext(context); } context.endElement(); } public void setCachedService(SOAPService service) { cachedService = service; } public Vector getTypeMappings() { return typeMappings; } public void setTypeMappings(Vector typeMappings) { this.typeMappings = typeMappings; } public void deployToRegistry(WSDDDeployment registry) { registry.addService(this); // Register the name of the service as a valid namespace, just for // backwards compatibility registry.registerNamespaceForService(getQName().getLocalPart(), this); for (int i = 0; i < namespaces.size(); i++) { String namespace = (String) namespaces.elementAt(i); registry.registerNamespaceForService(namespace, this); } super.deployToRegistry(registry); } public void removeNamespaceMappings(WSDDDeployment registry) { for (int i = 0; i < namespaces.size(); i++) { String namespace = (String) namespaces.elementAt(i); registry.removeNamespaceMapping(namespace); } registry.removeNamespaceMapping(getQName().getLocalPart()); } public TypeMapping getTypeMapping(String encodingStyle) { // If type mapping registry not initialized yet, return null. if (tmr == null) { return null; } return (TypeMapping) tmr.getOrMakeTypeMapping(encodingStyle); } public WSDDJAXRPCHandlerInfoChain getHandlerInfoChain() { return _wsddHIchain; } public void setHandlerInfoChain(WSDDJAXRPCHandlerInfoChain hichain) { _wsddHIchain = hichain; } }
7,689
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDTypeMappingContainer.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; /** * A common interface for things which contain type mappings (i.e. services * and deployments). This simplifies the code in Admin for now. * * @author Glen Daniels (gdaniels@apache.org) */ public interface WSDDTypeMappingContainer { public void deployTypeMapping(WSDDTypeMapping mapping) throws WSDDException; }
7,690
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDBeanMapping.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; /** * A <code>WSDDBeanMapping</code> is simply a <code>WSDDTypeMapping</code> * which has preset values for the serializer and deserializer attributes. * * This enables the following slightly simplified syntax when expressing * a bean mapping: * * &lt;beanMapping qname="prefix:local" languageSpecificType="java:class"/&gt; * * @author Glen Daniels (gdaniels@apache.org) */ public class WSDDBeanMapping extends WSDDTypeMapping { /** * Default constructor * */ public WSDDBeanMapping() { } public WSDDBeanMapping(Element e) throws WSDDException { super(e); serializer = BEAN_SERIALIZER_FACTORY; deserializer = BEAN_DESERIALIZER_FACTORY; encodingStyle = null; } protected QName getElementName() { return QNAME_BEANMAPPING; } public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); String typeStr = context.qName2String(typeQName); attrs.addAttribute("", ATTR_LANG_SPEC_TYPE, ATTR_LANG_SPEC_TYPE, "CDATA", typeStr); String qnameStr = context.qName2String(qname); attrs.addAttribute("", ATTR_QNAME, ATTR_QNAME, "CDATA", qnameStr); context.startElement(WSDDConstants.QNAME_BEANMAPPING, attrs); context.endElement(); } }
7,691
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDConstants.java
/* * Copyright 2001-2005 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import javax.xml.namespace.QName; /** * */ public class WSDDConstants { public static final String BEAN_SERIALIZER_FACTORY = "org.apache.axis.encoding.ser.BeanSerializerFactory"; public static final String BEAN_DESERIALIZER_FACTORY = "org.apache.axis.encoding.ser.BeanDeserializerFactory"; public static final String ARRAY_SERIALIZER_FACTORY = "org.apache.axis.encoding.ser.ArraySerializerFactory"; public static final String ARRAY_DESERIALIZER_FACTORY = "org.apache.axis.encoding.ser.ArrayDeserializerFactory"; public static final String URI_WSDD = "http://xml.apache.org/axis/wsdd/"; // The following have a '/' appended to the end of NS_URI_WSDD_JAVA.. OK to fix? // .../java/wsdd/examples/from_SOAP_v2/addressBook.wsdd // .../java/wsdd/examples/from_SOAP_v2/ejbtest.wsdd // .../java/wsdd/examples/from_SOAP_v2/messaging.wsdd // .../java/wsdd/examples/from_SOAP_v2/mimetest.wsdd // .../java/wsdd/examples/from_SOAP_v2/stockquote.wsdd // .../java/wsdd/examples/from_SOAP_v2/testprovider.wsdd // .../java/wsdd/examples/servcieConfiguration_examples/sce_wsddScenario0.wsdd // .../java/wsdd/examples/servcieConfiguration_examples/sce_wsddScenario1.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario0.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario1.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario2.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario3.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario4.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario5.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario6.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario7.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario8.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario9.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario10.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario11.wsdd // .../java/wsdd/examples/chaining_examples/ch_wsddScenario12.wsdd public static final String URI_WSDD_JAVA = "http://xml.apache.org/axis/wsdd/providers/java"; public static final String URI_WSDD_HANDLER = "http://xml.apache.org/axis/wsdd/providers/handler"; public static final String URI_WSDD_WSDD_COM = "http://xml.apache.org/axis/wsdd/providers/com"; // the following namespace is used in .../java/wsdd/examples/from_SOAP_v2/calculator.wsdd // BUT that namespace ends with '/', this one doesn't. Which is right? public static final String URI_WSDD_WSDD_BSF = "http://xml.apache.org/axis/wsdd/providers/bsf"; public static final String NS_PREFIX_WSDD = ""; public static final String NS_PREFIX_WSDD_JAVA = "java"; public static final String PROVIDER_RPC = "RPC"; public static final String PROVIDER_MSG = "MSG"; public static final String PROVIDER_HANDLER = "Handler"; public static final String PROVIDER_EJB = "EJB"; public static final String PROVIDER_COM = "COM"; public static final String PROVIDER_BSF = "BSF"; public static final String PROVIDER_CORBA = "CORBA"; public static final String PROVIDER_RMI = "RMI"; public static final QName QNAME_JAVARPC_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_RPC); public static final QName QNAME_JAVAMSG_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_MSG); public static final QName QNAME_HANDLER_PROVIDER = new QName("", PROVIDER_HANDLER); public static final QName QNAME_EJB_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_EJB); public static final QName QNAME_COM_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_COM); public static final QName QNAME_BSF_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_BSF); public static final QName QNAME_CORBA_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_CORBA); public static final QName QNAME_RMI_PROVIDER = new QName(URI_WSDD_JAVA, PROVIDER_RMI); public static final String ELEM_WSDD_PARAM = "parameter"; public static final String ELEM_WSDD_DOC = "documentation"; public static final String ELEM_WSDD_DEPLOY = "deployment"; public static final String ELEM_WSDD_UNDEPLOY = "undeployment"; public static final String ELEM_WSDD_REQFLOW = "requestFlow"; public static final String ELEM_WSDD_RESPFLOW = "responseFlow"; public static final String ELEM_WSDD_FAULTFLOW = "faultFlow"; public static final String ELEM_WSDD_HANDLER = "handler"; public static final String ELEM_WSDD_CHAIN = "chain"; public static final String ELEM_WSDD_SERVICE = "service"; public static final String ELEM_WSDD_TRANSPORT = "transport"; public static final String ELEM_WSDD_GLOBAL = "globalConfiguration"; public static final String ELEM_WSDD_TYPEMAPPING = "typeMapping"; public static final String ELEM_WSDD_BEANMAPPING = "beanMapping"; public static final String ELEM_WSDD_ARRAYMAPPING = "arrayMapping"; public static final String ELEM_WSDD_OPERATION = "operation"; public static final String ELEM_WSDD_ELEMENTMAPPING = "elementMapping"; public static final String ELEM_WSDD_WSDLFILE = "wsdlFile"; public static final String ELEM_WSDD_NAMESPACE = "namespace"; public static final String ELEM_WSDD_ENDPOINTURL = "endpointURL"; public static final String ELEM_WSDD_JAXRPC_HANDLERINFO = "handlerInfo"; public static final String ELEM_WSDD_JAXRPC_CHAIN = "handlerInfoChain"; public static final String ELEM_WSDD_JAXRPC_ROLE = "role"; public static final String ELEM_WSDD_JAXRPC_HEADER = "header"; public static final String ELEM_WSDD_FAULT = "fault"; public static final String ELEM_WSDD_ROLE = "role"; public static final QName QNAME_PARAM = new QName(URI_WSDD, ELEM_WSDD_PARAM); public static final QName QNAME_DOC = new QName(URI_WSDD, ELEM_WSDD_DOC); public static final QName QNAME_DEPLOY = new QName(URI_WSDD, ELEM_WSDD_DEPLOY); public static final QName QNAME_UNDEPLOY = new QName(URI_WSDD, ELEM_WSDD_UNDEPLOY); public static final QName QNAME_REQFLOW = new QName(URI_WSDD, ELEM_WSDD_REQFLOW); public static final QName QNAME_RESPFLOW = new QName(URI_WSDD, ELEM_WSDD_RESPFLOW); public static final QName QNAME_FAULTFLOW = new QName(URI_WSDD, ELEM_WSDD_FAULTFLOW); public static final QName QNAME_HANDLER = new QName(URI_WSDD, ELEM_WSDD_HANDLER); public static final QName QNAME_CHAIN = new QName(URI_WSDD, ELEM_WSDD_CHAIN); public static final QName QNAME_SERVICE = new QName(URI_WSDD, ELEM_WSDD_SERVICE); public static final QName QNAME_TRANSPORT = new QName(URI_WSDD, ELEM_WSDD_TRANSPORT); public static final QName QNAME_GLOBAL = new QName(URI_WSDD, ELEM_WSDD_GLOBAL); public static final QName QNAME_TYPEMAPPING = new QName(URI_WSDD, ELEM_WSDD_TYPEMAPPING); public static final QName QNAME_BEANMAPPING = new QName(URI_WSDD, ELEM_WSDD_BEANMAPPING); public static final QName QNAME_ARRAYMAPPING = new QName(URI_WSDD, ELEM_WSDD_ARRAYMAPPING); public static final QName QNAME_OPERATION = new QName(URI_WSDD, ELEM_WSDD_OPERATION); public static final QName QNAME_ELEMENTMAPPING = new QName(URI_WSDD, ELEM_WSDD_ELEMENTMAPPING); public static final QName QNAME_WSDLFILE = new QName(URI_WSDD, ELEM_WSDD_WSDLFILE); public static final QName QNAME_NAMESPACE = new QName(URI_WSDD, ELEM_WSDD_NAMESPACE); public static final QName QNAME_ENDPOINTURL = new QName(URI_WSDD, ELEM_WSDD_ENDPOINTURL); public static final QName QNAME_JAXRPC_HANDLERINFO = new QName(URI_WSDD, ELEM_WSDD_JAXRPC_HANDLERINFO); public static final QName QNAME_JAXRPC_HANDLERINFOCHAIN = new QName(URI_WSDD, ELEM_WSDD_JAXRPC_CHAIN); public static final QName QNAME_JAXRPC_HEADER = new QName(URI_WSDD, ELEM_WSDD_JAXRPC_HEADER); public static final QName QNAME_JAXRPC_ROLE = new QName(URI_WSDD,ELEM_WSDD_JAXRPC_ROLE); public static final QName QNAME_FAULT = new QName(URI_WSDD, ELEM_WSDD_FAULT); public static final String ATTR_LANG_SPEC_TYPE = "languageSpecificType"; public static final String ATTR_QNAME = "qname"; public static final String ATTR_NAME = "name"; public static final String ATTR_TYPE = "type"; public static final String ATTR_VALUE = "value"; public static final String ATTR_LOCKED = "locked"; public static final String ATTR_RETQNAME = "returnQName"; public static final String ATTR_RETTYPE = "returnType"; public static final String ATTR_RETITEMQNAME = "returnItemQName"; public static final String ATTR_RETITEMTYPE = "returnItemType"; public static final String ATTR_ITEMQNAME = "itemQName"; public static final String ATTR_ITEMTYPE = "itemType"; public static final String ATTR_MODE = "mode"; public static final String ATTR_INHEADER = "inHeader"; public static final String ATTR_OUTHEADER = "outHeader"; public static final String ATTR_RETHEADER = "returnHeader"; public static final String ATTR_STYLE = "style"; public static final String ATTR_USE = "use"; public static final String ATTR_STREAMING = "streaming"; public static final String ATTR_ATTACHMENT_FORMAT = "attachment"; public static final String ATTR_PROVIDER = "provider"; public static final String ATTR_PIVOT = "pivot"; public static final String ATTR_SERIALIZER = "serializer"; public static final String ATTR_DESERIALIZER = "deserializer"; public static final String ATTR_ENCSTYLE = "encodingStyle"; public static final String ATTR_SOAPACTORNAME = "soapActorName"; public static final String ATTR_CLASSNAME = "classname"; public static final String ATTR_CLASS = "class"; public static final String ATTR_SOAPACTION = "soapAction"; public static final String ATTR_SOAP12ACTION = "action"; public static final String ATTR_MEP = "mep"; public static final String ATTR_INNER_TYPE = "innerType"; public static final String ATTR_INNER_NAME = "innerName"; }
7,692
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDDocumentation.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.io.IOException; /** * represents a WSDD documentation * All WSDDElement can have a documentation but it is used only for * Services, Operations and Parameters for now */ public class WSDDDocumentation extends WSDDElement { private String value; /** the documentation */ protected QName getElementName() { return WSDDConstants.QNAME_DOC; } public WSDDDocumentation(String value) { this.value = value; } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDDocumentation(Element e) throws WSDDException { super(e); value = XMLUtils.getChildCharacterData(e); } /** * get the documentation */ public String getValue() { return value; } /** * set the documentation */ public void setValue(String value) { this.value = value; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { context.startElement(QNAME_DOC, null); context.writeSafeString(value); context.endElement(); } }
7,693
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDResponseFlow.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.w3c.dom.Element; import javax.xml.namespace.QName; /** * */ public class WSDDResponseFlow extends WSDDChain { /** * Default constructor */ public WSDDResponseFlow() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDResponseFlow(Element e) throws WSDDException { super(e); } protected QName getElementName() { return WSDDConstants.QNAME_RESPFLOW; } }
7,694
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDChain.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import java.io.IOException; import java.util.Vector; import javax.xml.namespace.QName; import org.apache.axis.Chain; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.encoding.SerializationContext; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; /** * WSDD chain element * */ public class WSDDChain extends WSDDHandler { private Vector handlers = new Vector(); /** * Default constructor */ public WSDDChain() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDChain(Element e) throws WSDDException { super(e); // If we're simply a reference to an existing chain, return. // !!! should check to make sure it's a valid chain? if (type != null) return; Element [] elements = getChildElements(e, ELEM_WSDD_HANDLER); if (elements.length != 0) { for (int i = 0; i < elements.length; i++) { WSDDHandler handler = new WSDDHandler(elements[i]); addHandler(handler); } } elements = getChildElements(e, ELEM_WSDD_CHAIN); if (elements.length != 0) { for (int i = 0; i < elements.length; i++) { WSDDChain chain = new WSDDChain(elements[i]); addHandler(chain); } } } protected QName getElementName() { return WSDDConstants.QNAME_CHAIN; } /** * Add a Handler to the chain (at the end) */ public void addHandler(WSDDHandler handler) { handlers.add(handler); } /** * Obtain our handler list * * @return a Vector containing our Handlers */ public Vector getHandlers() { return handlers; } /** * Remove a Handler from the chain */ public void removeHandler(WSDDHandler victim) { handlers.remove(victim); } /** * Creates a new instance of this Chain * @param registry XXX * @return XXX * @throws ConfigurationException XXX */ public Handler makeNewInstance(EngineConfiguration registry) throws ConfigurationException { Chain c = new org.apache.axis.SimpleChain(); for (int n = 0; n < handlers.size(); n++) { WSDDHandler handler = (WSDDHandler)handlers.get(n); Handler h = handler.getInstance(registry); if ( h != null ) c.addHandler(h); else throw new ConfigurationException("Can't find handler name:'" + handler.getQName() + "' type:'"+ handler.getType() + "' in the registry"); } return c; } /** * Write this element out to a SerializationContext */ public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); QName name = getQName(); if (name != null) { attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", context.qName2String(name)); } if (getType() != null) { attrs.addAttribute("", ATTR_TYPE, ATTR_TYPE, "CDATA", context.qName2String(getType())); } context.startElement(getElementName(), attrs); for (int n = 0; n < handlers.size(); n++) { WSDDHandler handler = (WSDDHandler)handlers.get(n); handler.writeToContext(context); } context.endElement(); } public void deployToRegistry(WSDDDeployment registry) { if (getQName() != null) registry.addHandler(this); for (int n = 0; n < handlers.size(); n++) { WSDDHandler handler = (WSDDHandler)handlers.get(n); if (handler.getQName() != null) handler.deployToRegistry(registry); } } }
7,695
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDJAXRPCHandlerInfo.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.utils.Messages; import org.apache.axis.utils.XMLUtils; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * */ public class WSDDJAXRPCHandlerInfo extends WSDDElement { private String _classname; private Map _map; private QName[] _headers; /** * Default constructor */ public WSDDJAXRPCHandlerInfo() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDJAXRPCHandlerInfo(Element e) throws WSDDException { super(e); String classnameStr = e.getAttribute(ATTR_CLASSNAME); if (classnameStr != null && !classnameStr.equals("")) { _classname = classnameStr; } else throw new WSDDException(Messages.getMessage("noClassNameAttr00")); Element[] elements = getChildElements(e, ELEM_WSDD_PARAM); // instanciate an empty Map _map = new HashMap(); if (elements.length != 0) { // Load up the map for (int i = 0; i < elements.length; i++) { Element param = elements[i]; String pname = param.getAttribute(ATTR_NAME); String value = param.getAttribute(ATTR_VALUE); _map.put(pname, value); } } elements = getChildElements(e, ELEM_WSDD_JAXRPC_HEADER); if (elements.length != 0) { java.util.ArrayList headerList = new java.util.ArrayList(); for (int i = 0; i < elements.length; i++) { Element qElem = elements[i]; String headerStr = qElem.getAttribute(ATTR_QNAME); if (headerStr == null || headerStr.equals("")) throw new WSDDException(Messages.getMessage("noValidHeader")); QName headerQName = XMLUtils.getQNameFromString(headerStr, qElem); if (headerQName != null) headerList.add(headerQName); } QName[] headers = new QName[headerList.size()]; _headers = (QName[]) headerList.toArray(headers); } } protected QName getElementName() { return QNAME_JAXRPC_HANDLERINFO; } public String getHandlerClassName() { return _classname; } public void setHandlerClassName(String classname) { _classname = classname; } public Map getHandlerMap() { return _map; } public void setHandlerMap(Map map) { _map = map; } public QName[] getHeaders() { return _headers; } public void setHeaders(QName[] headers) { _headers = headers; } public void writeToContext(SerializationContext context) throws IOException { AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", ATTR_CLASSNAME, ATTR_CLASSNAME, "CDATA", _classname); context.startElement(WSDDConstants.QNAME_JAXRPC_HANDLERINFO, attrs); Map ht = _map; if (ht != null) { Set keys= ht.keySet(); Iterator iter = keys.iterator(); while (iter.hasNext()) { String name = (String) iter.next(); String value = (String) ht.get(name); attrs = new AttributesImpl(); attrs.addAttribute("",ATTR_NAME, ATTR_NAME, "CDATA", name); attrs.addAttribute("",ATTR_VALUE, ATTR_VALUE, "CDATA", value); context.startElement(WSDDConstants.QNAME_PARAM,attrs); context.endElement(); } } if (_headers != null) { for (int i=0 ; i < _headers.length ; i++) { QName qname = _headers[i]; attrs = new AttributesImpl(); attrs.addAttribute("",ATTR_QNAME,ATTR_QNAME,"CDATA",context.qName2String(qname)); context.startElement(WSDDConstants.QNAME_JAXRPC_HEADER,attrs); context.endElement(); } } context.endElement(); } }
7,696
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDDeployableItem.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.encoding.SerializationContext; import org.apache.axis.providers.java.JavaProvider; import org.apache.axis.utils.ClassUtils; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.LockableHashtable; import org.apache.axis.utils.XMLUtils; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.xml.sax.helpers.AttributesImpl; import javax.xml.namespace.QName; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * WSDD DeployableItem complexType * */ public abstract class WSDDDeployableItem extends WSDDElement { public static final int SCOPE_PER_ACCESS = 0; public static final int SCOPE_PER_REQUEST = 1; public static final int SCOPE_SINGLETON = 2; public static String [] scopeStrings = { "per-access", "per-request", "singleton" }; protected static Log log = LogFactory.getLog(WSDDDeployableItem.class.getName()); /** Our parameters */ protected LockableHashtable parameters; /** Our name */ protected QName qname; /** Our type */ protected QName type; /** Scope for this item (default is singleton) */ protected int scope = SCOPE_SINGLETON; /** Placeholder for hanging on to singleton object */ protected Handler singletonInstance = null; /** * Default constructor */ public WSDDDeployableItem() { } /** * * @param e (Element) XXX * @throws WSDDException XXX */ public WSDDDeployableItem(Element e) throws WSDDException { super(e); String name = e.getAttribute(ATTR_NAME); if (name != null && !name.equals("")) { // qname = XMLUtils.getQNameFromString(name, e); qname = new QName("", name); } String typeStr = e.getAttribute(ATTR_TYPE); if (typeStr != null && !typeStr.equals("")) { type = XMLUtils.getQNameFromString(typeStr, e); } // Figure out our scope - right now if a non-recognized scope // attribute appears, we will ignore it and use the default // scope. Is this right, or should we throw an error? String scopeStr = e.getAttribute(JavaProvider.OPTION_SCOPE); if (scopeStr != null) { for (int i = 0; i < scopeStrings.length; i++) { if (scopeStr.equals(scopeStrings[i])) { scope = i; break; } } } parameters = new LockableHashtable(); // Load up our params Element [] paramElements = getChildElements(e, ELEM_WSDD_PARAM); for (int i = 0; i < paramElements.length; i++) { Element param = paramElements[i]; String pname = param.getAttribute(ATTR_NAME); String value = param.getAttribute(ATTR_VALUE); String locked = param.getAttribute(ATTR_LOCKED); parameters.put(pname, value, JavaUtils.isTrueExplicitly(locked)); } } /** * * @param name XXX */ public void setName(String name) { qname = new QName(null, name); } public void setQName(QName qname) { this.qname = qname; } /** * * @return XXX */ public QName getQName() { return qname; } /** * * @return XXX */ public QName getType() { return type; } /** * * @param type XXX */ public void setType(QName type) { this.type = type; } /** * Set a parameter */ public void setParameter(String name, String value) { if (parameters == null) { parameters = new LockableHashtable(); } parameters.put(name, value); } /** * Get the value of one of our parameters */ public String getParameter(String name) { if (name == null || parameters == null) { return null; } return (String)parameters.get(name); } /** * Returns the config parameters as a hashtable (lockable) * @return XXX */ public LockableHashtable getParametersTable() { return parameters; } /** * Convenience method for using old deployment XML with WSDD. * This allows us to set the options directly after the Admin class * has parsed them out of the old format. */ public void setOptionsHashtable(Hashtable hashtable) { if (hashtable == null) return; parameters = new LockableHashtable(hashtable); } public void writeParamsToContext(SerializationContext context) throws IOException { if (parameters == null) return; Set entries = parameters.entrySet(); Iterator i = entries.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String name = (String) entry.getKey(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", ATTR_NAME, ATTR_NAME, "CDATA", name); attrs.addAttribute("", ATTR_VALUE, ATTR_VALUE, "CDATA", entry.getValue().toString()); if (parameters.isKeyLocked(name)) { attrs.addAttribute("", ATTR_LOCKED, ATTR_LOCKED, "CDATA", "true"); } context.startElement(QNAME_PARAM, attrs); context.endElement(); } } /** * * @param name XXX */ public void removeParameter(String name) { if (parameters != null) { parameters.remove(name); } } /** * * @param registry XXX * @return XXX * @throws ConfigurationException XXX */ public final Handler getInstance(EngineConfiguration registry) throws ConfigurationException { if (scope == SCOPE_SINGLETON) { synchronized (this) { if (singletonInstance == null) singletonInstance = getNewInstance(registry); } return singletonInstance; } return getNewInstance(registry); } private Handler getNewInstance(EngineConfiguration registry) throws ConfigurationException { QName type = getType(); if (type == null || WSDDConstants.URI_WSDD_JAVA.equals(type.getNamespaceURI())) { return makeNewInstance(registry); } else { return registry.getHandler(type); } } /** * Creates a new instance of this deployable. if the * java class is not found, the registry is queried to * find a suitable item * @param registry XXX * @return XXX * @throws ConfigurationException XXX */ protected Handler makeNewInstance(EngineConfiguration registry) throws ConfigurationException { Class c = null; Handler h = null; try { c = getJavaClass(); } catch (ClassNotFoundException e) { throw new ConfigurationException(e); } if (c != null) { try { h = (Handler)createInstance(c); } catch (Exception e) { throw new ConfigurationException(e); } if (h != null) { if ( qname != null ) h.setName(qname.getLocalPart()); h.setOptions(getParametersTable()); try{ h.init(); }catch(Exception e){ String msg=e + JavaUtils.LS + JavaUtils.stackToString(e); log.debug(msg); throw new ConfigurationException(e); }catch(Error e){ String msg=e + JavaUtils.LS + JavaUtils.stackToString(e); log.debug(msg); throw new ConfigurationException(msg); } } } else { // !!! Should never get here! h = registry.getHandler(getType()); } return h; } /** * * @param _class XXX * @return XXX */ Object createInstance(Class _class) throws InstantiationException, IllegalAccessException { return _class.newInstance(); } /** * * @return XXX * @throws ClassNotFoundException XXX */ public Class getJavaClass() throws ClassNotFoundException { QName type = getType(); if (type != null && URI_WSDD_JAVA.equals(type.getNamespaceURI())) { return ClassUtils.forName(type.getLocalPart()); } return null; } }
7,697
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDException.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.ConfigurationException; /** * */ public class WSDDException extends ConfigurationException { /** * * @param msg (String) XXX */ public WSDDException(String msg) { super(msg); } /** * * @param e (Exception) XXX */ public WSDDException(Exception e) { super(e); } }
7,698
0
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment
Create_ds/axis-axis1-java/axis-rt-core/src/main/java/org/apache/axis/deployment/wsdd/WSDDProvider.java
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.axis.deployment.wsdd; import org.apache.axis.EngineConfiguration; import org.apache.axis.Handler; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.deployment.wsdd.providers.WSDDComProvider; import org.apache.axis.deployment.wsdd.providers.WSDDHandlerProvider; import org.apache.axis.deployment.wsdd.providers.WSDDJavaCORBAProvider; import org.apache.axis.deployment.wsdd.providers.WSDDJavaEJBProvider; import org.apache.axis.deployment.wsdd.providers.WSDDJavaMsgProvider; import org.apache.axis.deployment.wsdd.providers.WSDDJavaRMIProvider; import org.apache.axis.deployment.wsdd.providers.WSDDJavaRPCProvider; import org.apache.axis.utils.JavaUtils; import org.apache.axis.utils.Messages; import org.apache.commons.discovery.ResourceNameIterator; import org.apache.commons.discovery.resource.ClassLoaders; import org.apache.commons.discovery.resource.names.DiscoverServiceNames; import org.apache.commons.logging.Log; import javax.xml.namespace.QName; import java.util.Hashtable; /** * WSDD provider element * * Represents the liason to the application being exposed * as a Web Service. * * Specific provider extension classes must be registered * by namespace URI. * * @author James Snell * @author Vishy Kasar */ public abstract class WSDDProvider { protected static Log log = LogFactory.getLog(WSDDProvider.class.getName()); // ** STATIC PROVIDER REGISTRY ** // private static final String PLUGABLE_PROVIDER_FILENAME = "org.apache.axis.deployment.wsdd.Provider"; /** XXX */ private static Hashtable providers = new Hashtable(); static { providers.put(WSDDConstants.QNAME_JAVARPC_PROVIDER, new WSDDJavaRPCProvider()); providers.put(WSDDConstants.QNAME_JAVAMSG_PROVIDER, new WSDDJavaMsgProvider()); providers.put(WSDDConstants.QNAME_HANDLER_PROVIDER, new WSDDHandlerProvider()); providers.put(WSDDConstants.QNAME_EJB_PROVIDER, new WSDDJavaEJBProvider()); providers.put(WSDDConstants.QNAME_COM_PROVIDER, new WSDDComProvider()); providers.put(WSDDConstants.QNAME_CORBA_PROVIDER, new WSDDJavaCORBAProvider()); providers.put(WSDDConstants.QNAME_RMI_PROVIDER, new WSDDJavaRMIProvider()); try { loadPluggableProviders(); } catch (Throwable t){ String msg=t + JavaUtils.LS + JavaUtils.stackToString(t); log.info(Messages.getMessage("exception01",msg)); } } /** Look for file META-INF/services/org.apache.axis.deployment.wsdd.Provider in all the JARS, get the classes listed in those files and add them to providers list if they are valid providers. Here is how the scheme would work. A company providing a new provider will jar up their provider related classes in a JAR file. The following file containing the name of the new provider class is also made part of this JAR file. META-INF/services/org.apache.axis.deployment.wsdd.Provider By making this JAR part of the webapp, the new provider will be automatically discovered. */ private static void loadPluggableProviders() { ClassLoader clzLoader = WSDDProvider.class.getClassLoader(); ClassLoaders loaders = new ClassLoaders(); loaders.put(clzLoader); DiscoverServiceNames dsn = new DiscoverServiceNames(loaders); ResourceNameIterator iter = dsn.findResourceNames(PLUGABLE_PROVIDER_FILENAME); while (iter.hasNext()) { String className = iter.nextResourceName(); try { Object o = Class.forName(className).newInstance(); if (o instanceof WSDDProvider) { WSDDProvider provider = (WSDDProvider) o; String providerName = provider.getName(); QName q = new QName(WSDDConstants.URI_WSDD_JAVA, providerName); providers.put(q, provider); } } catch (Exception e) { String msg=e + JavaUtils.LS + JavaUtils.stackToString(e); log.info(Messages.getMessage("exception01",msg)); continue; } } } /** * * @param uri XXX * @param prov XXX */ public static void registerProvider(QName uri, WSDDProvider prov) { providers.put(uri, prov); } /** * * @return XXX */ public WSDDOperation[] getOperations() { return null; } /** * * @param name XXX * @return XXX */ public WSDDOperation getOperation(String name) { return null; } /** * * @param registry XXX * @return XXX * @throws Exception XXX */ public static Handler getInstance(QName providerType, WSDDService service, EngineConfiguration registry) throws Exception { if (providerType == null) throw new WSDDException(Messages.getMessage("nullProvider00")); WSDDProvider provider = (WSDDProvider)providers.get(providerType); if (provider == null) { throw new WSDDException(Messages.getMessage("noMatchingProvider00", providerType.toString())); } return provider.newProviderInstance(service, registry); } /** * * @param registry XXX * @return XXX * @throws Exception XXX */ public abstract Handler newProviderInstance(WSDDService service, EngineConfiguration registry) throws Exception; public abstract String getName(); }
7,699