ORBUtility.java revision 608:7e06bf1dcb09
1/*
2 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.corba.se.impl.orbutil;
27
28import java.lang.Character;
29import java.lang.reflect.Field;
30import java.lang.reflect.Method;
31import java.rmi.NoSuchObjectException;
32import java.security.AccessController;
33import java.security.PermissionCollection;
34import java.security.Policy;
35import java.security.PrivilegedAction;
36import java.security.ProtectionDomain;
37import java.util.ArrayList;
38import java.util.Arrays;
39import java.util.Map;
40import java.util.List;
41import java.util.ListIterator;
42import java.util.Set;
43import java.util.Map.Entry;
44import java.util.Collection;
45import java.util.HashMap;
46import java.util.HashSet;
47import java.util.Hashtable;
48import java.util.Iterator;
49import java.util.Enumeration;
50import java.util.Properties;
51import java.util.IdentityHashMap;
52import java.util.StringTokenizer;
53import java.util.NoSuchElementException;
54
55import javax.rmi.CORBA.ValueHandler;
56import javax.rmi.CORBA.ValueHandlerMultiFormat;
57import javax.rmi.CORBA.Util;
58
59import org.omg.CORBA.StructMember ;
60import org.omg.CORBA.TypeCode ;
61import org.omg.CORBA.Any ;
62import org.omg.CORBA.TCKind ;
63import org.omg.CORBA.SystemException ;
64import org.omg.CORBA.CompletionStatus ;
65import org.omg.CORBA.DATA_CONVERSION ;
66import org.omg.CORBA.BAD_PARAM ;
67import org.omg.CORBA.BAD_OPERATION ;
68import org.omg.CORBA.INTERNAL ;
69import org.omg.CORBA.TypeCodePackage.BadKind ;
70import org.omg.CORBA.portable.OutputStream ;
71import org.omg.CORBA.portable.InputStream ;
72
73import com.sun.corba.se.pept.transport.ContactInfoList ;
74
75import com.sun.corba.se.spi.ior.IOR ;
76import com.sun.corba.se.spi.presentation.rmi.StubAdapter ;
77import com.sun.corba.se.spi.orb.ORB ;
78import com.sun.corba.se.spi.orb.ORBVersion ;
79import com.sun.corba.se.spi.orb.ORBVersionFactory ;
80import com.sun.corba.se.spi.protocol.CorbaClientDelegate ;
81import com.sun.corba.se.spi.protocol.CorbaMessageMediator;
82import com.sun.corba.se.spi.transport.CorbaContactInfoList ;
83import com.sun.corba.se.spi.logging.CORBALogDomains ;
84import com.sun.corba.se.spi.ior.iiop.IIOPProfile;
85import com.sun.corba.se.spi.ior.iiop.IIOPProfileTemplate;
86
87import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
88import com.sun.corba.se.impl.corba.CORBAObjectImpl ;
89import com.sun.corba.se.impl.logging.ORBUtilSystemException ;
90import com.sun.corba.se.impl.logging.OMGSystemException ;
91import com.sun.corba.se.impl.ior.iiop.JavaSerializationComponent;
92
93import sun.corba.SharedSecrets;
94
95/**
96 *  Handy class full of static functions that don't belong in util.Utility for pure ORB reasons.
97 */
98public final class ORBUtility {
99    private ORBUtility() {}
100
101    private static ORBUtilSystemException wrapper = ORBUtilSystemException.get(
102        CORBALogDomains.UTIL ) ;
103    private static OMGSystemException omgWrapper = OMGSystemException.get(
104        CORBALogDomains.UTIL ) ;
105
106    private static StructMember[] members = null;
107
108    private static StructMember[] systemExceptionMembers (ORB orb) {
109        if (members == null) {
110            members = new StructMember[3];
111            members[0] = new StructMember("id", orb.create_string_tc(0), null);
112            members[1] = new StructMember("minor", orb.get_primitive_tc(TCKind.tk_long), null);
113            members[2] = new StructMember("completed", orb.get_primitive_tc(TCKind.tk_long), null);
114        }
115        return members;
116    }
117
118    private static TypeCode getSystemExceptionTypeCode(ORB orb, String repID, String name) {
119        synchronized (TypeCode.class) {
120            return orb.create_exception_tc(repID, name, systemExceptionMembers(orb));
121        }
122    }
123
124    private static boolean isSystemExceptionTypeCode(TypeCode type, ORB orb) {
125        StructMember[] systemExceptionMembers = systemExceptionMembers(orb);
126        try {
127            return (type.kind().value() == TCKind._tk_except &&
128                    type.member_count() == 3 &&
129                    type.member_type(0).equal(systemExceptionMembers[0].type) &&
130                    type.member_type(1).equal(systemExceptionMembers[1].type) &&
131                    type.member_type(2).equal(systemExceptionMembers[2].type));
132        } catch (BadKind ex) {
133            return false;
134        } catch (org.omg.CORBA.TypeCodePackage.Bounds ex) {
135            return false;
136        }
137    }
138
139    /**
140     * Static method for writing a CORBA standard exception to an Any.
141     * @param any The Any to write the SystemException into.
142     */
143    public static void insertSystemException(SystemException ex, Any any) {
144        OutputStream out = any.create_output_stream();
145        ORB orb = (ORB)(out.orb());
146        String name = ex.getClass().getName();
147        String repID = ORBUtility.repositoryIdOf(name);
148        out.write_string(repID);
149        out.write_long(ex.minor);
150        out.write_long(ex.completed.value());
151        any.read_value(out.create_input_stream(),
152            getSystemExceptionTypeCode(orb, repID, name));
153    }
154
155    public static SystemException extractSystemException(Any any) {
156        InputStream in = any.create_input_stream();
157        ORB orb = (ORB)(in.orb());
158        if ( ! isSystemExceptionTypeCode(any.type(), orb)) {
159            throw wrapper.unknownDsiSysex(CompletionStatus.COMPLETED_MAYBE);
160        }
161        return ORBUtility.readSystemException(in);
162    }
163
164    /**
165     * Return default ValueHandler
166     */
167    public static ValueHandler createValueHandler() {
168        return Util.createValueHandler();
169    }
170
171    /**
172     * Returns true if it was accurately determined that the remote ORB is
173     * a foreign (non-JavaSoft) ORB.  Note:  If passed the ORBSingleton, this
174     * will return false.
175     */
176    public static boolean isForeignORB(ORB orb)
177    {
178        if (orb == null)
179            return false;
180
181        try {
182            return orb.getORBVersion().equals(ORBVersionFactory.getFOREIGN());
183        } catch (SecurityException se) {
184            return false;
185        }
186    }
187
188    /** Unmarshal a byte array to an integer.
189        Assume the bytes are in BIGENDIAN order.
190        i.e. array[offset] is the most-significant-byte
191        and  array[offset+3] is the least-significant-byte.
192        @param array The array of bytes.
193        @param offset The offset from which to start unmarshalling.
194    */
195    public static int bytesToInt(byte[] array, int offset)
196    {
197        int b1, b2, b3, b4;
198
199        b1 = (array[offset++] << 24) & 0xFF000000;
200        b2 = (array[offset++] << 16) & 0x00FF0000;
201        b3 = (array[offset++] << 8)  & 0x0000FF00;
202        b4 = (array[offset++] << 0)  & 0x000000FF;
203
204        return (b1 | b2 | b3 | b4);
205    }
206
207    /** Marshal an integer to a byte array.
208        The bytes are in BIGENDIAN order.
209        i.e. array[offset] is the most-significant-byte
210        and  array[offset+3] is the least-significant-byte.
211        @param array The array of bytes.
212        @param offset The offset from which to start marshalling.
213    */
214    public static void intToBytes(int value, byte[] array, int offset)
215    {
216        array[offset++] = (byte)((value >>> 24) & 0xFF);
217        array[offset++] = (byte)((value >>> 16) & 0xFF);
218        array[offset++] = (byte)((value >>> 8) & 0xFF);
219        array[offset++] = (byte)((value >>> 0) & 0xFF);
220    }
221
222    /** Converts an Ascii Character into Hexadecimal digit
223     */
224    public static int hexOf( char x )
225    {
226        int val;
227
228        val = x - '0';
229        if (val >=0 && val <= 9)
230            return val;
231
232        val = (x - 'a') + 10;
233        if (val >= 10 && val <= 15)
234            return val;
235
236        val = (x - 'A') + 10;
237        if (val >= 10 && val <= 15)
238            return val;
239
240        throw wrapper.badHexDigit() ;
241    }
242
243    // method moved from util.Utility
244
245    /**
246     * Static method for writing a CORBA standard exception to a stream.
247     * @param strm The OutputStream to use for marshaling.
248     */
249    public static void writeSystemException(SystemException ex, OutputStream strm)
250    {
251        String s;
252
253        s = repositoryIdOf(ex.getClass().getName());
254        strm.write_string(s);
255        strm.write_long(ex.minor);
256        strm.write_long(ex.completed.value());
257    }
258
259    /**
260     * Static method for reading a CORBA standard exception from a stream.
261     * @param strm The InputStream to use for unmarshaling.
262     */
263    public static SystemException readSystemException(InputStream strm)
264    {
265        try {
266            String name = classNameOf(strm.read_string());
267            SystemException ex = (SystemException)SharedSecrets.
268                getJavaCorbaAccess().loadClass(name).newInstance();
269            ex.minor = strm.read_long();
270            ex.completed = CompletionStatus.from_int(strm.read_long());
271            return ex;
272        } catch ( Exception ex ) {
273            throw wrapper.unknownSysex( CompletionStatus.COMPLETED_MAYBE, ex );
274        }
275    }
276
277    /**
278     * Get the class name corresponding to a particular repository Id.
279     * This is used by the system to unmarshal (instantiate) the
280     * appropriate exception class for an marshaled as the value of
281     * its repository Id.
282     * @param repositoryId The repository Id for which we want a class name.
283     */
284    public static String classNameOf(String repositoryId)
285    {
286        String className=null;
287
288        className = (String) exceptionClassNames.get(repositoryId);
289        if (className == null)
290            className = "org.omg.CORBA.UNKNOWN";
291
292        return className;
293    }
294
295    /**
296     * Return true if this repositoryId is a SystemException.
297     * @param repositoryId The repository Id to check.
298     */
299    public static boolean isSystemException(String repositoryId)
300    {
301        String className=null;
302
303        className = (String) exceptionClassNames.get(repositoryId);
304        if (className == null)
305            return false;
306        else
307            return true;
308    }
309
310    /**
311     * @return the Java serialization encoding version.
312     */
313    public static byte getEncodingVersion(ORB orb, IOR ior) {
314
315        // Is Java serialization enabled?
316        // Check the JavaSerializationComponent (tagged component)
317        // in the IIOPProfile. If present, the peer ORB's GIOP is capable
318        // of using Java serialization instead of CDR serialization.
319        // In such a case, use Java serialization, iff the java serialization
320        // versions match.
321
322        if (orb.getORBData().isJavaSerializationEnabled()) {
323            IIOPProfile prof = ior.getProfile();
324            IIOPProfileTemplate profTemp =
325                (IIOPProfileTemplate) prof.getTaggedProfileTemplate();
326            java.util.Iterator iter = profTemp.iteratorById(
327                                  ORBConstants.TAG_JAVA_SERIALIZATION_ID);
328            if (iter.hasNext()) {
329                JavaSerializationComponent jc =
330                    (JavaSerializationComponent) iter.next();
331                byte jcVersion = jc.javaSerializationVersion();
332                if (jcVersion >= Message.JAVA_ENC_VERSION) {
333                    return Message.JAVA_ENC_VERSION;
334                } else if (jcVersion > Message.CDR_ENC_VERSION) {
335                    return jc.javaSerializationVersion();
336                } else {
337                    // throw error?
338                    // Since encodingVersion is <= 0 (CDR_ENC_VERSION).
339                }
340            }
341        }
342        return Message.CDR_ENC_VERSION; // default
343    }
344
345    /**
346     * Get the repository id corresponding to a particular class.
347     * This is used by the system to write the
348     * appropriate repository id for a system exception.
349     * @param name The class name of the system exception.
350     */
351    public static String repositoryIdOf(String name)
352    {
353        String id;
354
355        id = (String) exceptionRepositoryIds.get(name);
356        if (id == null)
357            id = "IDL:omg.org/CORBA/UNKNOWN:1.0";
358
359        return id;
360    }
361
362    private static final Hashtable exceptionClassNames = new Hashtable();
363    private static final Hashtable exceptionRepositoryIds = new Hashtable();
364
365    static {
366
367        //
368        // construct repositoryId -> className hashtable
369        //
370        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_CONTEXT:1.0",
371                                "org.omg.CORBA.BAD_CONTEXT");
372        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_INV_ORDER:1.0",
373                                "org.omg.CORBA.BAD_INV_ORDER");
374        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_OPERATION:1.0",
375                                "org.omg.CORBA.BAD_OPERATION");
376        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_PARAM:1.0",
377                                "org.omg.CORBA.BAD_PARAM");
378        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_TYPECODE:1.0",
379                                "org.omg.CORBA.BAD_TYPECODE");
380        exceptionClassNames.put("IDL:omg.org/CORBA/COMM_FAILURE:1.0",
381                                "org.omg.CORBA.COMM_FAILURE");
382        exceptionClassNames.put("IDL:omg.org/CORBA/DATA_CONVERSION:1.0",
383                                "org.omg.CORBA.DATA_CONVERSION");
384        exceptionClassNames.put("IDL:omg.org/CORBA/IMP_LIMIT:1.0",
385                                "org.omg.CORBA.IMP_LIMIT");
386        exceptionClassNames.put("IDL:omg.org/CORBA/INTF_REPOS:1.0",
387                                "org.omg.CORBA.INTF_REPOS");
388        exceptionClassNames.put("IDL:omg.org/CORBA/INTERNAL:1.0",
389                                "org.omg.CORBA.INTERNAL");
390        exceptionClassNames.put("IDL:omg.org/CORBA/INV_FLAG:1.0",
391                                "org.omg.CORBA.INV_FLAG");
392        exceptionClassNames.put("IDL:omg.org/CORBA/INV_IDENT:1.0",
393                                "org.omg.CORBA.INV_IDENT");
394        exceptionClassNames.put("IDL:omg.org/CORBA/INV_OBJREF:1.0",
395                                "org.omg.CORBA.INV_OBJREF");
396        exceptionClassNames.put("IDL:omg.org/CORBA/MARSHAL:1.0",
397                                "org.omg.CORBA.MARSHAL");
398        exceptionClassNames.put("IDL:omg.org/CORBA/NO_MEMORY:1.0",
399                                "org.omg.CORBA.NO_MEMORY");
400        exceptionClassNames.put("IDL:omg.org/CORBA/FREE_MEM:1.0",
401                                "org.omg.CORBA.FREE_MEM");
402        exceptionClassNames.put("IDL:omg.org/CORBA/NO_IMPLEMENT:1.0",
403                                "org.omg.CORBA.NO_IMPLEMENT");
404        exceptionClassNames.put("IDL:omg.org/CORBA/NO_PERMISSION:1.0",
405                                "org.omg.CORBA.NO_PERMISSION");
406        exceptionClassNames.put("IDL:omg.org/CORBA/NO_RESOURCES:1.0",
407                                "org.omg.CORBA.NO_RESOURCES");
408        exceptionClassNames.put("IDL:omg.org/CORBA/NO_RESPONSE:1.0",
409                                "org.omg.CORBA.NO_RESPONSE");
410        exceptionClassNames.put("IDL:omg.org/CORBA/OBJ_ADAPTER:1.0",
411                                "org.omg.CORBA.OBJ_ADAPTER");
412        exceptionClassNames.put("IDL:omg.org/CORBA/INITIALIZE:1.0",
413                                "org.omg.CORBA.INITIALIZE");
414        exceptionClassNames.put("IDL:omg.org/CORBA/PERSIST_STORE:1.0",
415                                "org.omg.CORBA.PERSIST_STORE");
416        exceptionClassNames.put("IDL:omg.org/CORBA/TRANSIENT:1.0",
417                                "org.omg.CORBA.TRANSIENT");
418        exceptionClassNames.put("IDL:omg.org/CORBA/UNKNOWN:1.0",
419                                "org.omg.CORBA.UNKNOWN");
420        exceptionClassNames.put("IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0",
421                                "org.omg.CORBA.OBJECT_NOT_EXIST");
422
423        // SystemExceptions from OMG Transactions Service Spec
424        exceptionClassNames.put("IDL:omg.org/CORBA/INVALID_TRANSACTION:1.0",
425                                "org.omg.CORBA.INVALID_TRANSACTION");
426        exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_REQUIRED:1.0",
427                                "org.omg.CORBA.TRANSACTION_REQUIRED");
428        exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_ROLLEDBACK:1.0",
429                                "org.omg.CORBA.TRANSACTION_ROLLEDBACK");
430
431        // from portability RTF 98-07-01.txt
432        exceptionClassNames.put("IDL:omg.org/CORBA/INV_POLICY:1.0",
433                                "org.omg.CORBA.INV_POLICY");
434
435        // from orbrev/00-09-01 (CORBA 2.4 Draft Specification)
436        exceptionClassNames.
437            put("IDL:omg.org/CORBA/TRANSACTION_UNAVAILABLE:1.0",
438                                "org.omg.CORBA.TRANSACTION_UNAVAILABLE");
439        exceptionClassNames.put("IDL:omg.org/CORBA/TRANSACTION_MODE:1.0",
440                                "org.omg.CORBA.TRANSACTION_MODE");
441
442        // Exception types introduced between CORBA 2.4 and 3.0
443        exceptionClassNames.put("IDL:omg.org/CORBA/CODESET_INCOMPATIBLE:1.0",
444                                "org.omg.CORBA.CODESET_INCOMPATIBLE");
445        exceptionClassNames.put("IDL:omg.org/CORBA/REBIND:1.0",
446                                "org.omg.CORBA.REBIND");
447        exceptionClassNames.put("IDL:omg.org/CORBA/TIMEOUT:1.0",
448                                "org.omg.CORBA.TIMEOUT");
449        exceptionClassNames.put("IDL:omg.org/CORBA/BAD_QOS:1.0",
450                                "org.omg.CORBA.BAD_QOS");
451
452        // Exception types introduced in CORBA 3.0
453        exceptionClassNames.put("IDL:omg.org/CORBA/INVALID_ACTIVITY:1.0",
454                                "org.omg.CORBA.INVALID_ACTIVITY");
455        exceptionClassNames.put("IDL:omg.org/CORBA/ACTIVITY_COMPLETED:1.0",
456                                "org.omg.CORBA.ACTIVITY_COMPLETED");
457        exceptionClassNames.put("IDL:omg.org/CORBA/ACTIVITY_REQUIRED:1.0",
458                                "org.omg.CORBA.ACTIVITY_REQUIRED");
459
460        //
461        // construct className -> repositoryId hashtable
462        //
463        Enumeration keys = exceptionClassNames.keys();
464        java.lang.Object s;
465        String rId;
466        String cName;
467
468        try{
469            while (keys.hasMoreElements()) {
470                s = keys.nextElement();
471                rId = (String) s;
472                cName = (String) exceptionClassNames.get(rId);
473                exceptionRepositoryIds.put (cName, rId);
474            }
475        } catch (NoSuchElementException e) { }
476    }
477
478    /** Parse a version string such as "1.1.6" or "jdk1.2fcs" into
479        a version array of integers {1, 1, 6} or {1, 2}.
480        A string of "n." or "n..m" is equivalent to "n.0" or "n.0.m" respectively.
481    */
482    public static int[] parseVersion(String version) {
483        if (version == null)
484            return new int[0];
485        char[] s = version.toCharArray();
486        //find the maximum span of the string "n.n.n..." where n is an integer
487        int start = 0;
488        for (; start < s.length  && (s[start] < '0' || s[start] > '9'); ++start)
489            if (start == s.length)      //no digit found
490                return new int[0];
491        int end = start + 1;
492        int size = 1;
493        for (; end < s.length; ++end)
494            if (s[end] == '.')
495                ++size;
496            else if (s[end] < '0' || s[end] > '9')
497                break;
498        int[] val = new int[size];
499        for (int i = 0; i < size; ++i) {
500            int dot = version.indexOf('.', start);
501            if (dot == -1 || dot > end)
502                dot = end;
503            if (start >= dot)   //cases like "n." or "n..m"
504                val[i] = 0;     //convert equivalent to "n.0" or "n.0.m"
505            else
506                val[i] = Integer.parseInt(version.substring(start, dot));
507            start = dot + 1;
508        }
509        return val;
510    }
511
512    /** Compare two version arrays.
513        Return 1, 0 or -1 if v1 is greater than, equal to, or less than v2.
514    */
515    public static int compareVersion(int[] v1, int[] v2) {
516        if (v1 == null)
517            v1 = new int[0];
518        if (v2 == null)
519            v2 = new int[0];
520        for (int i = 0; i < v1.length; ++i) {
521            if (i >= v2.length || v1[i] > v2[i])        //v1 is longer or greater than v2
522                return 1;
523            if (v1[i] < v2[i])
524                return -1;
525        }
526        return v1.length == v2.length ? 0 : -1;
527    }
528
529    /** Compare two version strings.
530        Return 1, 0 or -1 if v1 is greater than, equal to, or less than v2.
531    */
532    public static synchronized int compareVersion(String v1, String v2) {
533        return compareVersion(parseVersion(v1), parseVersion(v2));
534    }
535
536    private static String compressClassName( String name )
537    {
538        // Note that this must end in . in order to be renamed correctly.
539        String prefix = "com.sun.corba.se." ;
540        if (name.startsWith( prefix ) ) {
541            return "(ORB)." + name.substring( prefix.length() ) ;
542        } else
543            return name ;
544    }
545
546    // Return a compressed representation of the thread name.  This is particularly
547    // useful on the server side, where there are many SelectReaderThreads, and
548    // we need a short unambiguous name for such threads.
549    public static String getThreadName( Thread thr )
550    {
551        if (thr == null)
552            return "null" ;
553
554        // This depends on the formatting in SelectReaderThread and CorbaConnectionImpl.
555        // Pattern for SelectReaderThreads:
556        // SelectReaderThread CorbaConnectionImpl[ <host> <post> <state>]
557        // Any other pattern in the Thread's name is just returned.
558        String name = thr.getName() ;
559        StringTokenizer st = new StringTokenizer( name ) ;
560        int numTokens = st.countTokens() ;
561        if (numTokens != 5)
562            return name ;
563
564        String[] tokens = new String[numTokens] ;
565        for (int ctr=0; ctr<numTokens; ctr++ )
566            tokens[ctr] = st.nextToken() ;
567
568        if( !tokens[0].equals("SelectReaderThread"))
569            return name ;
570
571        return "SelectReaderThread[" + tokens[2] + ":" + tokens[3] + "]" ;
572    }
573
574    private static String formatStackTraceElement( StackTraceElement ste )
575    {
576        return compressClassName( ste.getClassName() ) + "." + ste.getMethodName() +
577            (ste.isNativeMethod() ? "(Native Method)" :
578             (ste.getFileName() != null && ste.getLineNumber() >= 0 ?
579              "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")" :
580              (ste.getFileName() != null ?  "("+ste.getFileName()+")" : "(Unknown Source)")));
581    }
582
583    private static void printStackTrace( StackTraceElement[] trace )
584    {
585        System.out.println( "    Stack Trace:" ) ;
586        // print the stack trace, ommitting the zeroth element, which is
587        // always this method.
588        for ( int ctr = 1; ctr < trace.length; ctr++ ) {
589            System.out.print( "        >" ) ;
590            System.out.println( formatStackTraceElement( trace[ctr] ) ) ;
591        }
592    }
593
594    //
595    // Implements all dprint calls in this package.
596    //
597    public static synchronized void dprint(java.lang.Object obj, String msg) {
598        System.out.println(
599            compressClassName( obj.getClass().getName() ) + "("  +
600            getThreadName( Thread.currentThread() ) + "): " + msg);
601    }
602
603    public static synchronized void dprint(String className, String msg) {
604        System.out.println(
605            compressClassName( className ) + "("  +
606            getThreadName( Thread.currentThread() ) + "): " + msg);
607    }
608
609    public synchronized void dprint(String msg) {
610        ORBUtility.dprint(this, msg);
611    }
612
613    public static synchronized void dprintTrace(Object obj, String msg) {
614        ORBUtility.dprint(obj, msg);
615
616        Throwable thr = new Throwable() ;
617        printStackTrace( thr.getStackTrace() ) ;
618    }
619
620    public static synchronized void dprint(java.lang.Object caller,
621        String msg, Throwable t)
622    {
623        System.out.println(
624            compressClassName( caller.getClass().getName() ) +
625            '(' + Thread.currentThread() + "): " + msg);
626
627        if (t != null)
628            printStackTrace( t.getStackTrace() ) ;
629    }
630
631    public static String[] concatenateStringArrays( String[] arr1, String[] arr2 )
632    {
633        String[] result = new String[
634            arr1.length + arr2.length ] ;
635
636        for (int ctr = 0; ctr<arr1.length; ctr++)
637            result[ctr] = arr1[ctr] ;
638
639        for (int ctr = 0; ctr<arr2.length; ctr++)
640            result[ctr + arr1.length] = arr2[ctr] ;
641
642        return result ;
643    }
644
645    /**
646     * Throws the CORBA equivalent of a java.io.NotSerializableException
647     *
648     * Duplicated from util/Utility for Pure ORB reasons.  There are two
649     * reasons for this:
650     *
651     * 1) We can't introduce dependencies on the util version from outside
652     * of the io/util packages since it will not exist in the pure ORB
653     * build running on JDK 1.3.x.
654     *
655     * 2) We need to pick up the correct minor code from OMGSystemException.
656     */
657    public static void throwNotSerializableForCorba(String className) {
658        throw omgWrapper.notSerializable( CompletionStatus.COMPLETED_MAYBE,
659            className ) ;
660    }
661
662    /**
663     * Returns the maximum stream format version supported by our
664     * ValueHandler.
665     */
666    public static byte getMaxStreamFormatVersion() {
667        ValueHandler vh = Util.createValueHandler();
668
669        if (!(vh instanceof javax.rmi.CORBA.ValueHandlerMultiFormat))
670            return ORBConstants.STREAM_FORMAT_VERSION_1;
671        else
672            return ((ValueHandlerMultiFormat)vh).getMaximumStreamFormatVersion();
673    }
674
675    public static CorbaClientDelegate makeClientDelegate( IOR ior )
676    {
677        ORB orb = ior.getORB() ;
678        CorbaContactInfoList ccil = orb.getCorbaContactInfoListFactory().create( ior ) ;
679        CorbaClientDelegate del = orb.getClientDelegateFactory().create(ccil);
680        return del ;
681    }
682
683    /** This method is used to create untyped object references.
684    */
685    public static org.omg.CORBA.Object makeObjectReference( IOR ior )
686    {
687        CorbaClientDelegate del = makeClientDelegate( ior ) ;
688        org.omg.CORBA.Object objectImpl = new CORBAObjectImpl() ;
689        StubAdapter.setDelegate( objectImpl, del ) ;
690        return objectImpl ;
691    }
692
693    /** This method obtains an IOR from a CORBA object reference.
694    * It will return null if obj is a local object, a null object,
695    * or an object implemented by a different ORB.  It will
696    * throw BAD_OPERATION if obj is an unconnected RMI-IIOP object.
697    * @return IOR the IOR that represents this objref.  This will
698    * never be null.
699    * @exception BAD_OPERATION (from oi._get_delegate) if obj is a
700    * normal objref, but does not have a delegate set.
701    * @exception BAD_PARAM if obj is a local object, or else was
702    * created by a foreign ORB.
703    */
704    public static IOR getIOR( org.omg.CORBA.Object obj )
705    {
706        if (obj == null)
707            throw wrapper.nullObjectReference() ;
708
709        IOR ior = null ;
710        if (StubAdapter.isStub(obj)) {
711            org.omg.CORBA.portable.Delegate del = StubAdapter.getDelegate(
712                obj ) ;
713
714            if (del instanceof CorbaClientDelegate) {
715                CorbaClientDelegate cdel = (CorbaClientDelegate)del ;
716                ContactInfoList cil = cdel.getContactInfoList() ;
717
718                if (cil instanceof CorbaContactInfoList) {
719                    CorbaContactInfoList ccil = (CorbaContactInfoList)cil ;
720                    ior = ccil.getTargetIOR() ;
721                    if (ior == null)
722                        throw wrapper.nullIor() ;
723
724                    return ior ;
725                } else {
726                    // This is our code, but the ContactInfoList is not a
727                    // CorbaContactInfoList.  This should not happen, because
728                    // we are in the CORBA application of the DCSA framework.
729                    // This is a coding error, and thus an INTERNAL exception
730                    // should be thrown.
731                    // XXX needs minor code
732                    throw new INTERNAL() ;
733                }
734            }
735
736            // obj is implemented by a foreign ORB, because the Delegate is not a
737            // ClientDelegate.
738            // XXX this case could be handled by marshalling and
739            // unmarshalling.  However, object_to_string cannot be used
740            // here, as it is implemented with getIOR.  Note that this
741            // will require access to an ORB, so that we can create streams
742            // as needed.  The ORB is available simply as io._orb().
743            throw wrapper.objrefFromForeignOrb() ;
744        } else
745            throw wrapper.localObjectNotAllowed() ;
746    }
747
748    /** Obtains an IOR for the object reference obj, first connecting it to
749    * the ORB if necessary.
750    * @return IOR the IOR that represents this objref.  This will
751    * never be null.
752    * @exception BAD_OPERATION if the object could not be connected,
753    * if a connection attempt was needed.
754    * @exception BAD_PARAM if obj is a local object, or else was
755    * created by a foreign ORB.
756    */
757    public static IOR connectAndGetIOR( ORB orb, org.omg.CORBA.Object obj )
758    {
759        IOR result ;
760        try {
761            result = getIOR( obj ) ;
762        } catch (BAD_OPERATION bop) {
763            if (StubAdapter.isStub(obj)) {
764                try {
765                    StubAdapter.connect( obj, orb ) ;
766                } catch (java.rmi.RemoteException exc) {
767                    throw wrapper.connectingServant( exc ) ;
768                }
769            } else {
770                orb.connect( obj ) ;
771            }
772
773            result = getIOR( obj ) ;
774        }
775
776        return result ;
777    }
778
779    public static String operationNameAndRequestId(CorbaMessageMediator m)
780    {
781        return "op/" + m.getOperationName() + " id/" + m.getRequestId();
782    }
783
784    public static boolean isPrintable(char c)
785    {
786        if (Character.isJavaIdentifierStart(c)) {
787            // Letters and $ _
788            return true;
789        }
790        if (Character.isDigit(c)) {
791            return true;
792        }
793        switch (Character.getType(c)) {
794        case Character.MODIFIER_SYMBOL : return true; // ` ^
795        case Character.DASH_PUNCTUATION : return true; // -
796        case Character.MATH_SYMBOL : return true; // = ~ + | < >
797        case Character.OTHER_PUNCTUATION : return true; // !@#%&*;':",./?
798        case Character.START_PUNCTUATION : return true; // ( [ {
799        case Character.END_PUNCTUATION : return true; // ) ] }
800        }
801        return false;
802    }
803
804    public static String getClassSecurityInfo(final Class cl)
805    {
806        // Returns a String which looks similar to:
807        // PermissionCollection java.security.Permissions@1053693 ...
808        // (java.io.FilePermission <<ALL FILES>> ....)
809        // (java.io.FilePermission /export0/sunwappserv/lib/- ...)
810        // ... other permissions ...
811        // Domain ProtectionDomain  (file:/export0/sunwappserv/lib-)
812        // java.security.Permissions@141fedb (
813        // (java.io.FilePermission <<ALL FILES>> ...)
814        // (java.io.FilePermission /var/tmp//- ...)
815
816        String result =
817            (String)AccessController.doPrivileged(new PrivilegedAction() {
818                public java.lang.Object run() {
819                    StringBuffer sb = new StringBuffer(500);
820                    ProtectionDomain pd = cl.getProtectionDomain();
821                    Policy policy = Policy.getPolicy();
822                    PermissionCollection pc = policy.getPermissions(pd);
823                    sb.append("\nPermissionCollection ");
824                    sb.append(pc.toString());
825                    // Don't need to add 'Protection Domain' string, it's
826                    // in ProtectionDomain.toString() already.
827                    sb.append(pd.toString());
828                    return sb.toString();
829                }
830            });
831        return result;
832    }
833}
834
835// End of file.
836