repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/AttributeAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.lang.reflect.Method; import java.rmi.Remote; import java.util.Locale; import org.omg.CORBA.AttributeMode; /** * Attribute analysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class AttributeAnalysis extends AbstractAnalysis { /** * Attribute mode. */ private AttributeMode mode; /** * Java type. */ private Class cls; /** * Accessor Method. */ private Method accessor = null; /** * Mutator Method. * This is null for read-only attributes. */ private Method mutator = null; /** * Accessor method analysis. */ private OperationAnalysis accessorAnalysis = null; /** * Mutator method analysis. * This is null for read-only attributes. */ private OperationAnalysis mutatorAnalysis = null; /** * Create an attribute analysis. */ private AttributeAnalysis(String javaName, AttributeMode mode, Method accessor, Method mutator) throws RMIIIOPViolationException { super(Util.javaToIDLName(javaName), javaName); this.mode = mode; this.cls = accessor.getReturnType(); this.accessor = accessor; this.mutator = mutator; // Only do operation analysis if the attribute is in a remote interface. if (accessor.getDeclaringClass().isInterface() && Remote.class.isAssignableFrom(accessor.getDeclaringClass())) { accessorAnalysis = new OperationAnalysis(accessor); if (mutator != null) { mutatorAnalysis = new OperationAnalysis(mutator); } setIDLName(getIDLName()); // Fix operation names } } /** * Create an attribute analysis for a read-only attribute. */ AttributeAnalysis(String javaName, Method accessor) throws RMIIIOPViolationException { this(javaName, AttributeMode.ATTR_READONLY, accessor, null); } /** * Create an attribute analysis for a read-write attribute. */ AttributeAnalysis(String javaName, Method accessor, Method mutator) throws RMIIIOPViolationException { this(javaName, AttributeMode.ATTR_NORMAL, accessor, mutator); } /** * Return my attribute mode. */ public AttributeMode getMode() { return mode; } /** * Return my Java type. */ public Class getCls() { return cls; } /** * Return my accessor method */ public Method getAccessor() { return accessor; } /** * Return my mutator method */ public Method getMutator() { return mutator; } /** * Return my accessor operation analysis */ public OperationAnalysis getAccessorAnalysis() { return accessorAnalysis; } /** * Return my mutator operation analysis */ public OperationAnalysis getMutatorAnalysis() { return mutatorAnalysis; } /** * Set my unqualified IDL name. * This also sets the names of the associated operations. */ void setIDLName(String idlName) { super.setIDLName(idlName); // If the first char is an uppercase letter and the second char is not // an uppercase letter, then convert the first char to lowercase. if (idlName.charAt(0) >= 0x41 && idlName.charAt(0) <= 0x5a && (idlName.length() <= 1 || idlName.charAt(1) < 0x41 || idlName.charAt(1) > 0x5a)) { idlName = idlName.substring(0, 1).toLowerCase(Locale.ENGLISH) + idlName.substring(1); } if (accessorAnalysis != null) accessorAnalysis.setIDLName("_get_" + idlName); if (mutatorAnalysis != null) mutatorAnalysis.setIDLName("_set_" + idlName); } }
5,074
27.194444
120
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/PrimitiveAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Analysis class for primitive types. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ public class PrimitiveAnalysis extends ClassAnalysis { public static final PrimitiveAnalysis voidAnalysis = new PrimitiveAnalysis(Void.TYPE, "void", "void"); public static final PrimitiveAnalysis booleanAnalysis = new PrimitiveAnalysis(Boolean.TYPE, "boolean", "boolean"); public static final PrimitiveAnalysis charAnalysis = new PrimitiveAnalysis(Character.TYPE, "wchar", "char"); public static final PrimitiveAnalysis byteAnalysis = new PrimitiveAnalysis(Byte.TYPE, "octet", "byte"); public static final PrimitiveAnalysis shortAnalysis = new PrimitiveAnalysis(Short.TYPE, "short", "short"); public static final PrimitiveAnalysis intAnalysis = new PrimitiveAnalysis(Integer.TYPE, "long", "int"); public static final PrimitiveAnalysis longAnalysis = new PrimitiveAnalysis(Long.TYPE, "long_long", "long"); public static final PrimitiveAnalysis floatAnalysis = new PrimitiveAnalysis(Float.TYPE, "float", "float"); public static final PrimitiveAnalysis doubleAnalysis = new PrimitiveAnalysis(Double.TYPE, "double", "double"); private PrimitiveAnalysis(final Class cls, final String idlName, final String javaName) { super(cls, idlName, javaName); } /** * Get a singleton instance representing one of the primitive types. */ public static PrimitiveAnalysis getPrimitiveAnalysis(final Class cls) { if (cls == null) throw IIOPLogger.ROOT_LOGGER.cannotAnalyzeNullClass(); if (cls == Void.TYPE) return voidAnalysis; if (cls == Boolean.TYPE) return booleanAnalysis; if (cls == Character.TYPE) return charAnalysis; if (cls == Byte.TYPE) return byteAnalysis; if (cls == Short.TYPE) return shortAnalysis; if (cls == Integer.TYPE) return intAnalysis; if (cls == Long.TYPE) return longAnalysis; if (cls == Float.TYPE) return floatAnalysis; if (cls == Double.TYPE) return doubleAnalysis; throw IIOPLogger.ROOT_LOGGER.notAPrimitive(cls.getName()); } }
3,483
41.487805
118
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ParameterAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import org.omg.CORBA.ParameterMode; /** * Parameter analysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ public class ParameterAnalysis extends AbstractAnalysis { /** * Java type of parameter. */ private final Class cls; /** * IDL type name of parameter type. */ private final String typeIDLName; ParameterAnalysis(final String javaName, final Class cls) throws RMIIIOPViolationException { super(javaName); this.cls = cls; typeIDLName = Util.getTypeIDLName(cls); } /** * Return my attribute mode. */ public ParameterMode getMode() { // 1.3.4.4 says we always map to IDL "in" parameters. return ParameterMode.PARAM_IN; } /** * Return my Java type. */ public Class getCls() { return cls; } /** * Return the IDL type name of my parameter type. */ public String getTypeIDLName() { return typeIDLName; } }
2,197
27.545455
97
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/RmiIdlUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Iterator; /** * This class contains a bunch of methods taken from * org.jboss.verifier.strategy.AbstractVerifier. There they are declared * as instance methods. I copied them to this class and made them static here * in order to call them as utility methods, without having to create a * verifier instance, * * @author <a href="mailto:juha.lindfors@jboss.org">Juha Lindfors</a> * @author Aaron Mulder (ammulder@alumni.princeton.edu) * @author Vinay Menon (menonv@cpw.co.uk) * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @version $Revision: 81018 $ */ public class RmiIdlUtil { public static boolean hasLegalRMIIIOPArguments(Method method) { Class[] params = method.getParameterTypes(); for (int i = 0; i < params.length; ++i) if (!isRMIIIOPType(params[i])) return false; return true; } public static boolean hasLegalRMIIIOPReturnType(Method method) { return isRMIIIOPType(method.getReturnType()); } public static boolean hasLegalRMIIIOPExceptionTypes(Method method) { /* * All checked exception classes used in method declarations * (other than java.rmi.RemoteException) MUST be conforming * RMI/IDL exception types. * * Spec 28.2.3 (4) */ Iterator it = Arrays.asList(method.getExceptionTypes()).iterator(); while (it.hasNext()) { Class exception = (Class) it.next(); if (!isRMIIDLExceptionType(exception)) return false; } return true; } /* * checks if the method's throws clause includes java.rmi.RemoteException * or a superclass of it. */ public static boolean throwsRemoteException(Method method) { Class[] exception = method.getExceptionTypes(); for (int i = 0; i < exception.length; ++i) if (exception[i].isAssignableFrom(java.rmi.RemoteException.class)) return true; return false; } /* * checks if a class's member (method, constructor or field) has a 'static' * modifier. */ public static boolean isStatic(Member member) { return (Modifier.isStatic(member.getModifiers())); } /* * checks if the given class is declared as static (inner classes only) */ public static boolean isStatic(Class c) { return (Modifier.isStatic(c.getModifiers())); } /* * checks if a class's member (method, constructor or field) has a 'final' * modifier. */ public static boolean isFinal(Member member) { return (Modifier.isFinal(member.getModifiers())); } /* * checks if the given class is declared as final */ public static boolean isFinal(Class c) { return (Modifier.isFinal(c.getModifiers())); } /* * checks if a class's member (method, constructor or field) has a 'public' * modifier. */ public static boolean isPublic(Member member) { return (Modifier.isPublic(member.getModifiers())); } /* * checks if the given class is declared as public */ public static boolean isPublic(Class c) { return (Modifier.isPublic(c.getModifiers())); } /** * Checks whether all the fields in the class are declared as public. */ public static boolean isAllFieldsPublic(Class c) { try { final Field[] list = c.getFields(); for (int i = 0; i < list.length; i++) if (!Modifier.isPublic(list[i].getModifiers())) return false; } catch (Exception e) { return false; } return true; } /* * checks if the given class is declared as abstract */ public static boolean isAbstract(Class c) { return (Modifier.isAbstract(c.getModifiers())); } public static boolean isRMIIIOPType(Class type) { /* * Java Language to IDL Mapping * ftp://ftp.omg.org/pub/docs/ptc/99-03-09.pdf * * A conforming RMI/IDL type is a Java type whose values * may be transmitted across an RMI/IDL remote interface at * run-time. A Java data type is a conforming RMI/IDL type * if it is: * * - one of the Java primitive types (see Primitive Types on page 28-2). * - a conforming remote interface (as defined in RMI/IDL Remote Interfaces on page 28-2). * - a conforming value type (as defined in RMI/IDL Value Types on page 28-4). * - an array of conforming RMI/IDL types (see RMI/IDL Arrays on page 28-5). * - a conforming exception type (see RMI/IDL Exception Types on page 28-5). * - a conforming CORBA object reference type (see CORBA Object Reference Types on page 28-6). * - a conforming IDL entity type see IDL Entity Types on page 28-6). */ /* * Primitive types. * * Spec 28.2.2 */ if (type.isPrimitive()) return true; /* * Conforming array. * * Spec 28.2.5 */ if (type.isArray()) return isRMIIIOPType(type.getComponentType()); /* * Conforming CORBA reference type * * Spec 28.2.7 */ if (org.omg.CORBA.Object.class.isAssignableFrom(type)) return true; /* * Conforming IDL Entity type * * Spec 28.2.8 */ if (org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(type)) return true; /* * Conforming remote interface. * * Spec 28.2.3 */ if (isRMIIDLRemoteInterface(type)) return true; /* * Conforming exception. * * Spec 28.2.6 */ if (isRMIIDLExceptionType(type)) return true; /* * Conforming value type. * * Spec 28.2.4 */ if (isRMIIDLValueType(type)) return true; return false; } public static boolean isRMIIDLRemoteInterface(Class type) { /* * If does not implement java.rmi.Remote, cannot be valid RMI-IDL * remote interface. */ if (!java.rmi.Remote.class.isAssignableFrom(type)) return false; Iterator methodIterator = Arrays.asList(type.getMethods()).iterator(); while (methodIterator.hasNext()) { Method m = (Method) methodIterator.next(); /* * All methods in the interface MUST throw * java.rmi.RemoteException or a superclass of it. * * Spec 28.2.3 (2) */ if (!throwsRemoteException(m)) { return false; } /* * All checked exception classes used in method declarations * (other than java.rmi.RemoteException) MUST be conforming * RMI/IDL exception types. * * Spec 28.2.3 (4) */ Iterator it = Arrays.asList(m.getExceptionTypes()).iterator(); while (it.hasNext()) { Class exception = (Class) it.next(); if (!isRMIIDLExceptionType(exception)) return false; } } /* * The constant values defined in the interface MUST be * compile-time types of RMI/IDL primitive types or String. * * Spec 28.2.3 (6) */ Iterator fieldIterator = Arrays.asList(type.getFields()).iterator(); while (fieldIterator.hasNext()) { Field f = (Field) fieldIterator.next(); if (f.getType().isPrimitive()) continue; if (f.getType().equals(String.class)) continue; return false; } return true; } public static boolean isAbstractInterface(Class type) { /* * It must be a Java interface. */ if (!type.isInterface()) return false; /* * It must not be the interface of a CORBA object. */ if (org.omg.CORBA.Object.class.isAssignableFrom(type)) return false; /* * It must not extend java.rmi.Remote directly or indirectly. */ if (java.rmi.Remote.class.isAssignableFrom(type)) return false; Iterator methodIterator = Arrays.asList(type.getMethods()).iterator(); while (methodIterator.hasNext()) { Method m = (Method) methodIterator.next(); /* * All methods MUST throw java.rmi.RemoteException * or a superclass of it. */ if (!throwsRemoteException(m)) { return false; } } return true; } public static boolean isRMIIDLExceptionType(Class type) { /* * A conforming RMI/IDL Exception class MUST be a checked * exception class and MUST be a valid RMI/IDL value type. * * Spec 28.2.6 */ if (!Throwable.class.isAssignableFrom(type)) return false; if (Error.class.isAssignableFrom(type)) return false; if (RuntimeException.class.isAssignableFrom(type)) return false; if (!isRMIIDLValueType(type)) return false; return true; } public static boolean isRMIIDLValueType(Class type) { /* * A value type MUST NOT either directly or indirectly implement the * java.rmi.Remote interface. * * Spec 28.2.4 (4) */ if (java.rmi.Remote.class.isAssignableFrom(type)) return false; /* * It cannot be a CORBA object. */ if (org.omg.CORBA.Object.class.isAssignableFrom(type)) return false; /* * If class is a non-static inner class then its containing class must * also be a conforming RMI/IDL value type. * * Spec 2.8.4 (3) */ if (type.getDeclaringClass() != null && isStatic(type) && !isRMIIDLValueType(type.getDeclaringClass())) { return false; } return true; } public static boolean isAbstractValueType(Class type) { if (!type.isInterface()) return false; if (org.omg.CORBA.Object.class.isAssignableFrom(type)) return false; boolean cannotBeRemote = false; boolean cannotBeAbstractInterface = false; if (java.rmi.Remote.class.isAssignableFrom(type)) { cannotBeAbstractInterface = true; } else { cannotBeRemote = true; } Iterator methodIterator = Arrays.asList(type.getMethods()).iterator(); while (methodIterator.hasNext()) { Method m = (Method) methodIterator.next(); if (!throwsRemoteException(m)) { cannotBeAbstractInterface = true; cannotBeRemote = true; break; } Iterator it = Arrays.asList(m.getExceptionTypes()).iterator(); while (it.hasNext()) { Class exception = (Class) it.next(); if (!isRMIIDLExceptionType(exception)) { cannotBeRemote = true; break; } } } if (!cannotBeRemote) { Iterator fieldIterator = Arrays.asList(type.getFields()).iterator(); while (fieldIterator.hasNext()) { Field f = (Field) fieldIterator.next(); if (f.getType().isPrimitive()) continue; if (f.getType().equals(String.class)) continue; cannotBeRemote = true; break; } } return cannotBeRemote && cannotBeAbstractInterface; } public static void rethrowIfCorbaSystemException(Throwable e) { RuntimeException re; if (e instanceof java.rmi.MarshalException) re = new org.omg.CORBA.MARSHAL(e.toString()); else if (e instanceof java.rmi.NoSuchObjectException) re = new org.omg.CORBA.OBJECT_NOT_EXIST(e.toString()); else if (e instanceof java.rmi.AccessException) re = new org.omg.CORBA.NO_PERMISSION(e.toString()); else if (e instanceof jakarta.transaction.TransactionRequiredException) re = new org.omg.CORBA.TRANSACTION_REQUIRED(e.toString()); else if (e instanceof jakarta.transaction.TransactionRolledbackException) re = new org.omg.CORBA.TRANSACTION_ROLLEDBACK(e.toString()); else if (e instanceof jakarta.transaction.InvalidTransactionException) re = new org.omg.CORBA.INVALID_TRANSACTION(e.toString()); else if (e instanceof org.omg.CORBA.SystemException) re = (org.omg.CORBA.SystemException) e; else return; re.setStackTrace(e.getStackTrace()); throw re; } }
14,403
29.070981
102
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/WorkCacheManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Instances of this class cache the most complex analyse types. * <p/> * The analyse types cached are: * <ul> * <li><code>InterfaceAnalysis</code> for interfaces.</li> * <li><code>ValueAnalysis</code> for value types.</li> * <li><code>ExceptionAnalysis</code> for exceptions.</li> * </ul> * <p/> * Besides caching work already done, this caches work in progress, * as we need to know about this to handle cyclic graphs of analyses. * When a thread re-enters the <code>getAnalysis()</code> method, an * unfinished analysis will be returned if the same thread is already * working on this analysis. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ class WorkCacheManager { /** * The analysis constructor of our analysis class. * This constructor takes a single argument of type <code>Class</code>. */ private final Constructor constructor; /** * The analysis initializer of our analysis class. * This method takes no arguments, and is named doAnalyze. */ private final Method initializer; /** * This maps the classes of completely done analyses to soft * references of their analysis. */ private final Map<Class, SoftReference<ContainerAnalysis>> workDone; /** * This maps the classes of analyses in progress to their * analysis. */ private final Map<InProgressKey, ContainerAnalysis> workInProgress; private final Map<ClassLoader, Set<Class<?>>> classesByLoader; /** * Create a new work cache manager. * * @param cls The class of the analysis type we cache here. */ WorkCacheManager(final Class cls) { // Find the constructor and initializer. try { constructor = cls.getDeclaredConstructor(new Class[]{Class.class}); initializer = cls.getDeclaredMethod("doAnalyze"); } catch (NoSuchMethodException ex) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(ex); } workDone = new HashMap<Class, SoftReference<ContainerAnalysis>>(); workInProgress = new HashMap<InProgressKey, ContainerAnalysis>(); classesByLoader = new HashMap<ClassLoader, Set<Class<?>>>(); } public void clearClassLoader(final ClassLoader cl) { Set<Class<?>> classes = classesByLoader.remove(cl); if(classes != null) { for(Class<?> clazz : classes) { workDone.remove(clazz); } } } /** * Returns an analysis. * If the calling thread is currently doing an analysis of this * class, an unfinished analysis is returned. */ ContainerAnalysis getAnalysis(final Class cls) throws RMIIIOPViolationException { ContainerAnalysis ret = null; boolean created = false; try { synchronized (this) { ret = lookupDone(cls); if (ret != null) { return ret; } // is it work-in-progress? final ContainerAnalysis inProgress = workInProgress.get(new InProgressKey(cls, Thread.currentThread())); if (inProgress != null) { return inProgress; // return unfinished // Do not wait for the other thread: We may deadlock // Double work is better that deadlock... } ret = createWorkInProgress(cls); } created = true; // Do the work doTheWork(cls, ret); } finally { // We did it synchronized (this) { if(created) { workInProgress.remove(new InProgressKey(cls, Thread.currentThread())); workDone.put(cls, new SoftReference<ContainerAnalysis>(ret)); ClassLoader classLoader = cls.getClassLoader(); if (classLoader != null) { Set<Class<?>> classes = classesByLoader.get(classLoader); if (classes == null) { classesByLoader.put(classLoader, classes = new HashSet<Class<?>>()); } classes.add(cls); } } notifyAll(); } } return ret; } /** * Lookup an analysis in the fully done map. */ private ContainerAnalysis lookupDone(Class cls) { SoftReference ref = (SoftReference) workDone.get(cls); if (ref == null) return null; ContainerAnalysis ret = (ContainerAnalysis) ref.get(); if (ret == null) workDone.remove(cls); // clear map entry if soft ref. was cleared. return ret; } /** * Create new work-in-progress. */ private ContainerAnalysis createWorkInProgress(final Class cls) { final ContainerAnalysis analysis; try { analysis = (ContainerAnalysis) constructor.newInstance(cls); } catch (InstantiationException ex) { throw new RuntimeException(ex.toString()); } catch (IllegalAccessException ex) { throw new RuntimeException(ex.toString()); } catch (InvocationTargetException ex) { throw new RuntimeException(ex.toString()); } workInProgress.put(new InProgressKey(cls, Thread.currentThread()), analysis); return analysis; } private void doTheWork(final Class cls, final ContainerAnalysis ret) throws RMIIIOPViolationException { try { initializer.invoke(ret); } catch (Throwable t) { synchronized (this) { workInProgress.remove(new InProgressKey(cls, Thread.currentThread())); } if (t instanceof InvocationTargetException) // unwrap t = ((InvocationTargetException) t).getTargetException(); if (t instanceof RMIIIOPViolationException) throw (RMIIIOPViolationException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; throw new RuntimeException(t.toString()); } } private static class InProgressKey { final Class<?> clazz; final Thread thread; private InProgressKey(Class<?> clazz, Thread thread) { this.clazz = clazz; this.thread = thread; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InProgressKey that = (InProgressKey) o; if (clazz != null ? !clazz.equals(that.clazz) : that.clazz != null) return false; if (thread != null ? !thread.equals(that.thread) : that.thread != null) return false; return true; } @Override public int hashCode() { int result = clazz != null ? clazz.hashCode() : 0; result = 31 * result + (thread != null ? thread.hashCode() : 0); return result; } } }
8,603
34.118367
120
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/InterfaceAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Interface analysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ public class InterfaceAnalysis extends ContainerAnalysis { private boolean abstractInterface; private String[] allTypeIds; /** * Map of IDL operation names to operation analyses. */ Map<String, OperationAnalysis> operationAnalysisMap; private static WorkCacheManager cache = new WorkCacheManager(InterfaceAnalysis.class); public static InterfaceAnalysis getInterfaceAnalysis(Class cls) throws RMIIIOPViolationException { return (InterfaceAnalysis) cache.getAnalysis(cls); } public static void clearCache(final ClassLoader classLoader) { cache.clearClassLoader(classLoader); } protected InterfaceAnalysis(Class cls) { super(cls); } protected void doAnalyze() throws RMIIIOPViolationException { super.doAnalyze(); calculateOperationAnalysisMap(); fixupCaseNames(); } public boolean isAbstractInterface() { return abstractInterface; } public boolean isRmiIdlRemoteInterface() { return (!abstractInterface); } public String[] getAllTypeIds() { return (String[]) allTypeIds.clone(); } /** * Return a list of all the entries contained here. */ protected ArrayList getContainedEntries() { final ArrayList ret = new ArrayList(constants.length + attributes.length + operations.length); for (int i = 0; i < constants.length; ++i) ret.add(constants[i]); for (int i = 0; i < attributes.length; ++i) ret.add(attributes[i]); for (int i = 0; i < operations.length; ++i) ret.add(operations[i]); return ret; } /** * Analyse operations. * This will fill in the <code>operations</code> array. */ protected void analyzeOperations() throws RMIIIOPViolationException { if (!cls.isInterface()) throw IIOPLogger.ROOT_LOGGER.notAnInterface(cls.getName()); abstractInterface = RmiIdlUtil.isAbstractInterface(cls); calculateAllTypeIds(); int operationCount = 0; for (int i = 0; i < methods.length; ++i) if ((m_flags[i] & (M_READ | M_WRITE | M_READONLY)) == 0) ++operationCount; operations = new OperationAnalysis[operationCount]; operationCount = 0; for (int i = 0; i < methods.length; ++i) { if ((m_flags[i] & (M_READ | M_WRITE | M_READONLY)) == 0) { operations[operationCount] = new OperationAnalysis(methods[i]); ++operationCount; } } } /** * Calculate the map that maps IDL operation names to operation analyses. * Besides mapped operations, this map also contains the attribute * accessor and mutator operations. */ protected void calculateOperationAnalysisMap() { operationAnalysisMap = new HashMap(); OperationAnalysis oa; // Map the operations for (int i = 0; i < operations.length; ++i) { oa = operations[i]; operationAnalysisMap.put(oa.getIDLName(), oa); } // Map the attributes for (int i = 0; i < attributes.length; ++i) { AttributeAnalysis attr = attributes[i]; oa = attr.getAccessorAnalysis(); // Not having an accessor analysis means that // the attribute is not in a remote interface if (oa != null) { operationAnalysisMap.put(oa.getIDLName(), oa); oa = attr.getMutatorAnalysis(); if (oa != null) operationAnalysisMap.put(oa.getIDLName(), oa); } } } /** * Calculate the array containing all type ids of this interface, * in the format that org.omg.CORBA.portable.Servant._all_interfaces() * is expected to return. */ protected void calculateAllTypeIds() { if (!isRmiIdlRemoteInterface()) { allTypeIds = new String[0]; } else { ArrayList a = new ArrayList(); InterfaceAnalysis[] intfs = getInterfaces(); for (int i = 0; i < intfs.length; ++i) { String[] ss = intfs[i].getAllTypeIds(); for (int j = 0; j < ss.length; ++j) if (!a.contains(ss[j])) a.add(ss[j]); } allTypeIds = new String[a.size() + 1]; allTypeIds[0] = getRepositoryId(); for (int i = 1; i <= a.size(); ++i) allTypeIds[i] = (String) a.get(a.size() - i); } } }
6,015
31.344086
102
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/DelegatingStubFactoryFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import javax.rmi.CORBA.Tie; import com.sun.corba.se.impl.presentation.rmi.StubFactoryFactoryBase; import com.sun.corba.se.impl.presentation.rmi.StubFactoryFactoryProxyImpl; import com.sun.corba.se.impl.presentation.rmi.StubFactoryFactoryStaticImpl; import com.sun.corba.se.spi.presentation.rmi.PresentationManager; import org.wildfly.security.manager.WildFlySecurityManager; import java.security.AccessController; import java.security.PrivilegedAction; /** * Stub factory * * @author Stuart Douglas */ public class DelegatingStubFactoryFactory extends StubFactoryFactoryBase { private final PresentationManager.StubFactoryFactory staticFactory; private final PresentationManager.StubFactoryFactory dynamicFactory; private static volatile PresentationManager.StubFactoryFactory overriddenDynamicFactory; public DelegatingStubFactoryFactory() { staticFactory = new StubFactoryFactoryStaticImpl(); dynamicFactory = new StubFactoryFactoryProxyImpl(); } public PresentationManager.StubFactory createStubFactory(final String className, final boolean isIDLStub, final String remoteCodeBase, final Class expectedClass, final ClassLoader classLoader) { if(WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged(new PrivilegedAction<PresentationManager.StubFactory>() { @Override public PresentationManager.StubFactory run() { return getStubFactoryImpl(className, isIDLStub, remoteCodeBase, expectedClass, classLoader); } }); } else { return getStubFactoryImpl(className, isIDLStub, remoteCodeBase, expectedClass, classLoader); } } private PresentationManager.StubFactory getStubFactoryImpl(String className, boolean isIDLStub, String remoteCodeBase, Class<?> expectedClass, ClassLoader classLoader) { try { PresentationManager.StubFactory stubFactory = staticFactory.createStubFactory(className, isIDLStub, remoteCodeBase, expectedClass, classLoader); if (stubFactory != null) { return stubFactory; } } catch (Exception e) { } if (overriddenDynamicFactory != null) { return overriddenDynamicFactory.createStubFactory(className, isIDLStub, remoteCodeBase, expectedClass, classLoader); } else { return dynamicFactory.createStubFactory(className, isIDLStub, remoteCodeBase, expectedClass, classLoader); } } public Tie getTie(final Class cls) { if (WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged(new PrivilegedAction<Tie>() { @Override public Tie run() { return getTieImpl(cls); } }); } else { return getTieImpl(cls); } } private Tie getTieImpl(Class<?> cls) { try { Tie tie = staticFactory.getTie(cls); if (tie != null) { return tie; } } catch (Exception e) { } return dynamicFactory.getTie(cls); } public boolean createsDynamicStubs() { return true; } public static PresentationManager.StubFactoryFactory getOverriddenDynamicFactory() { return overriddenDynamicFactory; } public static void setOverriddenDynamicFactory(final PresentationManager.StubFactoryFactory overriddenDynamicFactory) { DelegatingStubFactoryFactory.overriddenDynamicFactory = overriddenDynamicFactory; } }
4,680
38.008333
198
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ExceptionAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Exception analysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ public class ExceptionAnalysis extends ValueAnalysis { private static WorkCacheManager cache = new WorkCacheManager(ExceptionAnalysis.class); private String exceptionRepositoryId; public static ExceptionAnalysis getExceptionAnalysis(Class cls) throws RMIIIOPViolationException { return (ExceptionAnalysis) cache.getAnalysis(cls); } public static void clearCache(final ClassLoader classLoader) { cache.clearClassLoader(classLoader); } protected ExceptionAnalysis(Class cls) { super(cls); } protected void doAnalyze() throws RMIIIOPViolationException { super.doAnalyze(); if (!Exception.class.isAssignableFrom(cls) || RuntimeException.class.isAssignableFrom(cls)) throw IIOPLogger.ROOT_LOGGER.badRMIIIOPExceptionType(cls.getName(), "1.2.6"); // calculate exceptionRepositoryId StringBuffer b = new StringBuffer("IDL:"); String pkgName = cls.getPackage().getName(); while (!"".equals(pkgName)) { int idx = pkgName.indexOf('.'); String n = (idx == -1) ? pkgName : pkgName.substring(0, idx); b.append(Util.javaToIDLName(n)).append('/'); pkgName = (idx == -1) ? "" : pkgName.substring(idx + 1); } String base = cls.getName(); base = base.substring(base.lastIndexOf('.') + 1); if (base.endsWith("Exception")) base = base.substring(0, base.length() - 9); base = Util.javaToIDLName(base + "Ex"); b.append(base).append(":1.0"); exceptionRepositoryId = b.toString(); } /** * Return the repository ID for the mapping of this analysis * to an exception. */ public String getExceptionRepositoryId() { return exceptionRepositoryId; } }
3,191
33.695652
89
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/OperationAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.rmi.Remote; import java.rmi.RemoteException; import java.lang.reflect.Method; import java.util.ArrayList; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Operation analysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class OperationAnalysis extends AbstractAnalysis { /** * The Method that this OperationAnalysis is mapping. */ private final Method method; /** * The mapped exceptions of this operation. */ private final ExceptionAnalysis[] mappedExceptions; /** * The parameters of this operation. */ private final ParameterAnalysis[] parameters; OperationAnalysis(final Method method) throws RMIIIOPViolationException { super(method.getName()); this.method = method; // Check if valid return type, IF it is a remote interface. Class retCls = method.getReturnType(); if (retCls.isInterface() && Remote.class.isAssignableFrom(retCls)) Util.isValidRMIIIOP(retCls); // Analyze exceptions Class[] ex = method.getExceptionTypes(); boolean gotRemoteException = false; ArrayList a = new ArrayList(); for (int i = 0; i < ex.length; ++i) { if (ex[i].isAssignableFrom(RemoteException.class)) gotRemoteException = true; if (Exception.class.isAssignableFrom(ex[i]) && !RuntimeException.class.isAssignableFrom(ex[i]) && !RemoteException.class.isAssignableFrom(ex[i])) a.add(ExceptionAnalysis.getExceptionAnalysis(ex[i])); // map this } if (!gotRemoteException && Remote.class.isAssignableFrom(method.getDeclaringClass())) throw IIOPLogger.ROOT_LOGGER.badRMIIIOPMethodSignature(getJavaName(), method.getDeclaringClass().getName(), "1.2.3"); final ExceptionAnalysis[] exceptions = new ExceptionAnalysis[a.size()]; mappedExceptions = (ExceptionAnalysis[]) a.toArray(exceptions); // Analyze parameters Class[] params = method.getParameterTypes(); parameters = new ParameterAnalysis[params.length]; for (int i = 0; i < params.length; ++i) { parameters[i] = new ParameterAnalysis("param" + (i + 1), params[i]); } } /** * Return my Java return type. */ public Class getReturnType() { return method.getReturnType(); } /** * Return my mapped Method. */ public Method getMethod() { return method; } /** * Return my mapped exceptions. */ public ExceptionAnalysis[] getMappedExceptions() { return (ExceptionAnalysis[]) mappedExceptions.clone(); } /** * Return my parameters. */ public ParameterAnalysis[] getParameters() { return (ParameterAnalysis[]) parameters.clone(); } }
4,133
33.165289
119
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/AbstractAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; /** * Abstract base class for all analysis classes. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ abstract class AbstractAnalysis { /** * My unqualified IDL name. */ private String idlName; /** * My unqualified java name. */ private final String javaName; AbstractAnalysis(String idlName, String javaName) { this.idlName = idlName; this.javaName = javaName; } AbstractAnalysis(String javaName) { this(Util.javaToIDLName(javaName), javaName); } /** * Return my unqualified IDL name. */ public String getIDLName() { return idlName; } /** * Return my unqualified java name. */ public String getJavaName() { return javaName; } /** * Set my unqualified IDL name. */ void setIDLName(String idlName) { this.idlName = idlName; } }
2,146
26.525641
72
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ClassAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Analysis class for classes. These define IDL types. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ public class ClassAnalysis extends AbstractAnalysis { /** * My java class. */ protected Class cls; /** * Analyze the given class, and return the analysis. * public static ClassAnalysis getClassAnalysis(Class cls) * throws RMIIIOPViolationException * { * if (cls == null) * throw new IllegalArgumentException("Cannot analyze NULL class."); * if (cls == java.lang.String.class || cls == java.lang.Object.class || * cls == java.lang.Class.class || cls == java.io.Serializable.class || * cls == java.io.Externalizable.class || * cls == java.rmi.Remote.class) * throw new IllegalArgumentException("Cannot analyze special class: " + * cls.getName()); * <p/> * if (cls.isPrimitive()) * return PrimitiveAnalysis.getPrimitiveAnalysis(cls); * <p/> * <p/> * if (cls.isInterface() && java.rmi.Remote.class.isAssignableFrom(cls)) * return InterfaceAnalysis.getInterfaceAnalysis(cls); * // TODO * throw new RuntimeException("ClassAnalysis.getClassAnalysis() TODO"); * } */ private static String javaNameOfClass(Class cls) { if (cls == null) throw IIOPLogger.ROOT_LOGGER.cannotAnalyzeNullClass(); String s = cls.getName(); return s.substring(s.lastIndexOf('.') + 1); } public ClassAnalysis(Class cls, String idlName, String javaName) { super(idlName, javaName); this.cls = cls; } public ClassAnalysis(Class cls, String javaName) { this(cls, Util.javaToIDLName(javaName), javaName); } public ClassAnalysis(Class cls) { this(cls, javaNameOfClass(cls)); } /** * Return my java class. */ public Class getCls() { return cls; } }
3,169
30.386139
80
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/Util.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.WeakHashMap; import org.omg.CORBA.Any; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * This is a RMI/IIOP metadata conversion utility class. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class Util { /** * Return the IDL type name for the given class. * Here we use the mapping for parameter types and return values. */ public static String getTypeIDLName(Class cls) throws RMIIIOPViolationException { if (cls.isPrimitive()) return PrimitiveAnalysis.getPrimitiveAnalysis(cls).getIDLName(); if (cls.isArray()) { // boxedRMI 1.3.6 Class componentClass = cls; int sequence = 0; while (componentClass.isArray()) { componentClass = componentClass.getComponentType(); ++sequence; } String idlName = getTypeIDLName(componentClass); int idx = idlName.lastIndexOf("::"); String idlModule = idlName.substring(0, idx + 2); String baseName = idlName.substring(idx + 2); return "::org::omg::boxedRMI" + idlModule + "seq" + sequence + "_" + baseName; } // special classes if (cls == String.class) return "::CORBA::WStringValue"; if (cls == Object.class) return "::java::lang::_Object"; if (cls == Class.class) return "::javax::rmi::CORBA::ClassDesc"; if (cls == Serializable.class) return "::java::io::Serializable"; if (cls == Externalizable.class) return "::java::io::Externalizable"; if (cls == java.rmi.Remote.class) return "::java::rmi::Remote"; if (cls == org.omg.CORBA.Object.class) return "::CORBA::Object"; // remote interface? if (cls.isInterface() && java.rmi.Remote.class.isAssignableFrom(cls)) { InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls); return ia.getIDLModuleName() + "::" + ia.getIDLName(); } // IDL interface? if (cls.isInterface() && org.omg.CORBA.Object.class.isAssignableFrom(cls) && org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(cls)) { InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls); return ia.getIDLModuleName() + "::" + ia.getIDLName(); } // exception? if (Throwable.class.isAssignableFrom(cls) && Exception.class.isAssignableFrom(cls) && !RuntimeException.class.isAssignableFrom(cls)) { ExceptionAnalysis ea = ExceptionAnalysis.getExceptionAnalysis(cls); return ea.getIDLModuleName() + "::" + ea.getIDLName(); } // got to be value ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls); return va.getIDLModuleName() + "::" + va.getIDLName(); } /** * Check if this class is valid for RMI/IIOP mapping. * This method will either throw an exception or return true. */ public static boolean isValidRMIIIOP(Class cls) throws RMIIIOPViolationException { if (cls.isPrimitive()) return true; if (cls.isArray()) return isValidRMIIIOP(cls.getComponentType()); // special interfaces if (cls == Serializable.class || cls == Externalizable.class) return true; // interface? if (cls.isInterface() && java.rmi.Remote.class.isAssignableFrom(cls)) { InterfaceAnalysis.getInterfaceAnalysis(cls); return true; } // exception? if (Throwable.class.isAssignableFrom(cls)) { if (Exception.class.isAssignableFrom(cls) && !RuntimeException.class.isAssignableFrom(cls)) { ExceptionAnalysis.getExceptionAnalysis(cls); } return true; } // special values if (cls == Object.class || cls == String.class || cls == Class.class) return true; // got to be value ValueAnalysis.getValueAnalysis(cls); return true; } /** * Insert a java primitive into an Any. * The primitive is assumed to be wrapped in one of the primitive * wrapper classes. */ public static void insertAnyPrimitive(Any any, Object primitive) { Class type = primitive.getClass(); if (type == Boolean.class) any.insert_boolean((Boolean) primitive); else if (type == Character.class) any.insert_wchar((Character) primitive); else if (type == Byte.class) any.insert_octet((Byte) primitive); else if (type == Short.class) any.insert_short((Short) primitive); else if (type == Integer.class) any.insert_long((Integer) primitive); else if (type == Long.class) any.insert_longlong((Long) primitive); else if (type == Float.class) any.insert_float((Float) primitive); else if (type == Double.class) any.insert_double((Double) primitive); else throw IIOPLogger.ROOT_LOGGER.notAPrimitive(type.getName()); } /** * Map Java name to IDL name, as per sections 1.3.2.3, 1.3.2.4 and * 1.3.2.2. * This only works for a single name component, without a qualifying * dot. */ public static String javaToIDLName(String name) { if (name == null || "".equals(name) || name.indexOf('.') != -1) throw IIOPLogger.ROOT_LOGGER.nameCannotBeNullEmptyOrQualified(); StringBuffer res = new StringBuffer(name.length()); if (name.charAt(0) == '_') res.append('J'); // 1.3.2.3 for (int i = 0; i < name.length(); ++i) { char c = name.charAt(i); if (isLegalIDLIdentifierChar(c)) res.append(c); else // 1.3.2.4 res.append('U').append(toHexString((int) c)); } String s = res.toString(); if (isReservedIDLKeyword(s)) return "_" + s; else return s; } /** * Return the IR global ID of the given class or interface. * This is described in section 1.3.5.7. * The returned string is in the RMI hashed format, like * "RMI:java.util.Hashtable:C03324C0EA357270:13BB0F25214AE4B8". */ public static String getIRIdentifierOfClass(Class cls) { if (cls.isPrimitive()) throw IIOPLogger.ROOT_LOGGER.primitivesHaveNoIRIds(); String result = (String) classIRIdentifierCache.get(cls); if (result != null) return result; String name = cls.getName(); StringBuffer b = new StringBuffer("RMI:"); for (int i = 0; i < name.length(); ++i) { char c = name.charAt(i); if (c < 256) b.append(c); else b.append("\\U").append(toHexString((int) c)); } long clsHash = getClassHashCode(cls); b.append(':').append(toHexString(clsHash)); ObjectStreamClass osClass = ObjectStreamClass.lookup(cls); if (osClass != null) { long serialVersionUID = osClass.getSerialVersionUID(); if (clsHash != serialVersionUID) b.append(':').append(toHexString(serialVersionUID)); } result = b.toString(); classIRIdentifierCache.put(cls, result); return result; } // Private ------------------------------------------------------- /** * A cache for calculated class hash codes. */ private static Map classHashCodeCache = Collections.synchronizedMap(new WeakHashMap()); /** * A cache for class IR identifiers. */ private static Map classIRIdentifierCache = Collections.synchronizedMap(new WeakHashMap()); /** * Reserved IDL keywords. * <p/> * Section 1.3.2.2 says that Java identifiers with these names * should have prepended an underscore. */ private static final String[] reservedIDLKeywords = new String[]{ "abstract", "any", "attribute", "boolean", "case", "char", "const", "context", "custom", "default", "double", "exception", "enum", "factory", "FALSE", "fixed", "float", "in", "inout", "interface", "local", "long", "module", "native", "Object", "octet", "oneway", "out", "private", "public", "raises", "readonly", "sequence", "short", "string", "struct", "supports", "switch", "TRUE", "truncatable", "typedef", "unsigned", "union", "ValueBase", "valuetype", "void", "wchar", "wstring" }; static { // Initialize caches classHashCodeCache = Collections.synchronizedMap(new WeakHashMap()); classIRIdentifierCache = Collections.synchronizedMap(new WeakHashMap()); } /** * Convert an integer to a 16-digit hex string. */ private static String toHexString(int i) { String s = Integer.toHexString(i).toUpperCase(Locale.ENGLISH); if (s.length() < 8) return "00000000".substring(8 - s.length()) + s; else return s; } /** * Convert a long to a 16-digit hex string. */ private static String toHexString(long l) { String s = Long.toHexString(l).toUpperCase(Locale.ENGLISH); if (s.length() < 16) return "0000000000000000".substring(16 - s.length()) + s; else return s; } /** * Determine if the argument is a reserved IDL keyword. */ private static boolean isReservedIDLKeyword(String s) { // TODO: faster lookup for (int i = 0; i < reservedIDLKeywords.length; ++i) if (reservedIDLKeywords[i].equals(s)) return true; return false; } /** * Determine if a <code>char</code> is a legal IDL identifier character. */ private static boolean isLegalIDLIdentifierChar(char c) { if (c >= 0x61 && c <= 0x7a) return true; // lower case letter if (c >= 0x30 && c <= 0x39) return true; // digit if (c >= 0x41 && c <= 0x5a) return true; // upper case letter if (c == '_') return true; // underscore return false; } /** * Return the class hash code, as specified in "The Common Object * Request Broker: Architecture and Specification" (01-02-33), * section 10.6.2. */ static long getClassHashCode(Class cls) { // The simple cases if (cls.isInterface()) return 0; if (!Serializable.class.isAssignableFrom(cls)) return 0; if (Externalizable.class.isAssignableFrom(cls)) return 1; // Try cache Long l = (Long) classHashCodeCache.get(cls); if (l != null) return l; // Has to calculate the hash. ByteArrayOutputStream baos = new ByteArrayOutputStream(256); DataOutputStream dos = new DataOutputStream(baos); // Step 1 Class superClass = cls.getSuperclass(); if (superClass != null && superClass != Object.class) { try { dos.writeLong(getClassHashCode(superClass)); } catch (IOException ex) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(ex); } } // Step 2 boolean hasWriteObject = false; try { Method m; int mods; m = cls.getDeclaredMethod("writeObject", new Class[]{ObjectOutputStream.class}); mods = m.getModifiers(); if (!Modifier.isPrivate(mods) && !Modifier.isStatic(mods)) hasWriteObject = true; } catch (NoSuchMethodException ex) { // ignore } try { dos.writeInt(hasWriteObject ? 2 : 1); } catch (IOException ex) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(ex); } // Step 3 Field[] fields = cls.getDeclaredFields(); SortedSet set = new TreeSet(new FieldComparator()); for (int i = 0; i < fields.length; ++i) { int mods = fields[i].getModifiers(); if (!Modifier.isStatic(mods) && !Modifier.isTransient(mods)) set.add(fields[i]); } Iterator iter = set.iterator(); try { while (iter.hasNext()) { Field f = (Field) iter.next(); dos.writeUTF(f.getName()); dos.writeUTF(getSignature(f.getType())); } } catch (IOException ex) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(ex); } // Convert to byte[] try { dos.flush(); } catch (IOException ex) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(ex); } byte[] bytes = baos.toByteArray(); // Calculate SHA digest MessageDigest digest; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw IIOPLogger.ROOT_LOGGER.unavailableSHADigest(ex); } digest.update(bytes); byte[] sha = digest.digest(); // Calculate hash as per section 10.6.2 long hash = 0; for (int i = 0; i < Math.min(8, sha.length); i++) { hash += (long) (sha[i] & 255) << (i * 8); } // Save in cache classHashCodeCache.put(cls, hash); return hash; } /** * Calculate the signature of a class, according to the Java VM * specification, section 4.3.2. */ private static String getSignature(Class cls) { if (cls.isArray()) return "[" + cls.getComponentType(); if (cls.isPrimitive()) { if (cls == Byte.TYPE) return "B"; if (cls == Character.TYPE) return "C"; if (cls == Double.TYPE) return "D"; if (cls == Float.TYPE) return "F"; if (cls == Integer.TYPE) return "I"; if (cls == Long.TYPE) return "J"; if (cls == Short.TYPE) return "S"; if (cls == Boolean.TYPE) return "Z"; throw IIOPLogger.ROOT_LOGGER.unknownPrimitiveType(cls.getName()); } return "L" + cls.getName().replace('.', '/') + ";"; } /** * Handle mappings for primitive types, as per section 1.3.3. */ static String primitiveTypeIDLName(Class type) { if (type == Void.TYPE) return "void"; if (type == Boolean.TYPE) return "boolean"; if (type == Character.TYPE) return "wchar"; if (type == Byte.TYPE) return "octet"; if (type == Short.TYPE) return "short"; if (type == Integer.TYPE) return "long"; if (type == Long.TYPE) return "long long"; if (type == Float.TYPE) return "float"; if (type == Double.TYPE) return "double"; throw IIOPLogger.ROOT_LOGGER.notAPrimitive(type.getName()); } // Inner classes ------------------------------------------------- /** * A <code>Comparator</code> for <code>Field</code>s, ordering the * fields according to the lexicographic ordering of their Java names. */ private static class FieldComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 == o2) return 0; String n1 = ((Field) o1).getName(); String n2 = ((Field) o2).getName(); return n1.compareTo(n2); } } }
18,363
29.863866
90
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ContainerAnalysis.java
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi; import java.io.Externalizable; import java.io.ObjectStreamClass; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Locale; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Common base class of ValueAnalysis and InterfaceAnalysis. * <p/> * Routines here are conforming to the "Java(TM) Language to IDL Mapping * Specification", version 1.1 (01-06-07). * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @author <a href="mailto:dimitris@jboss.org">Dimitris Andreadis</a> * @version $Revision: 63378 $ */ public abstract class ContainerAnalysis extends ClassAnalysis { /** * A cache for the fully qualified IDL name of the IDL module we * belong to. */ private String idlModuleName = null; /** * Flags a method as overloaded. */ protected final byte M_OVERLOADED = 1; /** * Flags a method as the accessor of a read-write property. */ protected final byte M_READ = 2; /** * Flags a method as the mutator of a read-write property. */ protected final byte M_WRITE = 4; /** * Flags a method as the accessor of a read-only property. */ protected final byte M_READONLY = 8; /** * Flags a method as being inherited. */ protected final byte M_INHERITED = 16; /** * Flags a method as being the writeObject() method * used for serialization. */ protected final byte M_WRITEOBJECT = 32; /** * Flags a field as being a constant (public final static). */ protected final byte F_CONSTANT = 1; /** * Flags a field as being the special <code> public final static * java.io.ObjectStreamField[] serialPersistentFields</code> field. */ protected final byte F_SPFFIELD = 2; /** * Array of all java methods. */ protected Method[] methods; /** * Array with flags for all java methods. */ protected byte[] m_flags; /** * Index of the mutator for read-write attributes. * Only entries <code>i</code> where <code>(m_flags[i]&M_READ) != 0</code> * are used. These entries contain the index of the mutator method * corresponding to the accessor method. */ protected int[] mutators; /** * Array of all java fields. */ protected Field[] fields; /** * Array with flags for all java fields. */ protected byte[] f_flags; /** * The class hash code, as specified in "The Common Object Request * Broker: Architecture and Specification" (01-02-33), section 10.6.2. */ protected long classHashCode = 0; /** * The repository ID. * This is in the RMI hashed format, like * "RMI:java.util.Hashtable:C03324C0EA357270:13BB0F25214AE4B8". */ protected String repositoryId; /** * The prefix and postfix of members repository ID. * These are used to calculate member repository IDs and are like * "RMI:java.util.Hashtable." and ":C03324C0EA357270:13BB0F25214AE4B8". */ protected String memberPrefix, memberPostfix; /** * Array of analysis of the interfaces implemented/extended here. */ protected InterfaceAnalysis[] interfaces; /** * Array of analysis of the abstract base valuetypes implemented/extended here. */ protected ValueAnalysis[] abstractBaseValuetypes; /** * Array of attributes. */ protected AttributeAnalysis[] attributes; /** * Array of Constants. */ protected ConstantAnalysis[] constants; /** * Array of operations. */ protected OperationAnalysis[] operations; protected ContainerAnalysis(Class cls) { super(cls); if (cls == Object.class || cls == Serializable.class || cls == Externalizable.class) throw IIOPLogger.ROOT_LOGGER.cannotAnalyzeSpecialClass(cls.getName()); this.cls = cls; } protected void doAnalyze() throws RMIIIOPViolationException { analyzeInterfaces(); analyzeMethods(); analyzeFields(); calculateClassHashCode(); calculateRepositoryId(); analyzeAttributes(); analyzeConstants(); analyzeOperations(); fixupOverloadedOperationNames(); } /** * Return the interfaces. */ public InterfaceAnalysis[] getInterfaces() { return (InterfaceAnalysis[]) interfaces.clone(); } /** * Return the abstract base valuetypes. */ public ValueAnalysis[] getAbstractBaseValuetypes() { return (ValueAnalysis[]) abstractBaseValuetypes.clone(); } /** * Return the attributes. */ public AttributeAnalysis[] getAttributes() { return (AttributeAnalysis[]) attributes.clone(); } /** * Return the constants. */ public ConstantAnalysis[] getConstants() { return (ConstantAnalysis[]) constants.clone(); } /** * Return the operations. */ public OperationAnalysis[] getOperations() { return (OperationAnalysis[]) operations.clone(); } /** * Return the repository ID. */ public String getRepositoryId() { return repositoryId; } /** * Return a repository ID for a member. * * @param memberName The Java name of the member. */ public String getMemberRepositoryId(String memberName) { return memberPrefix + escapeIRName(memberName) + memberPostfix; } /** * Return the fully qualified IDL module name that this * analysis should be placed in. */ public String getIDLModuleName() { if (idlModuleName == null) { String pkgName = cls.getPackage().getName(); StringBuffer b = new StringBuffer(); while (!"".equals(pkgName)) { int idx = pkgName.indexOf('.'); String n = (idx == -1) ? pkgName : pkgName.substring(0, idx); b.append("::").append(Util.javaToIDLName(n)); pkgName = (idx == -1) ? "" : pkgName.substring(idx + 1); } idlModuleName = b.toString(); } return idlModuleName; } // Protected ----------------------------------------------------- /** * Convert an integer to a 16-digit hex string. */ protected String toHexString(int i) { String s = Integer.toHexString(i).toUpperCase(Locale.ENGLISH); if (s.length() < 8) return "00000000".substring(0, 8 - s.length()) + s; else return s; } /** * Convert a long to a 16-digit hex string. */ protected String toHexString(long l) { String s = Long.toHexString(l).toUpperCase(Locale.ENGLISH); if (s.length() < 16) return "0000000000000000".substring(0, 16 - s.length()) + s; else return s; } /** * Check if a method is an accessor. */ protected boolean isAccessor(Method m) { Class returnType = m.getReturnType(); // JBAS-4473, look for get<name>() String name = m.getName(); if (!(name.startsWith("get") && name.length() > "get".length()) && (!(name.startsWith("is") && name.length() > "is".length()) || !(returnType == Boolean.TYPE))) return false; if (returnType == Void.TYPE) return false; if (m.getParameterCount() != 0) return false; return hasNonAppExceptions(m); } /** * Check if a method is a mutator. */ protected boolean isMutator(Method m) { // JBAS-4473, look for set<name>() String name = m.getName(); if (!(name.startsWith("set") && name.length() > "set".length())) return false; if (m.getReturnType() != Void.TYPE) return false; if (m.getParameterCount() != 1) return false; return hasNonAppExceptions(m); } /** * Check if a method throws anything checked other than * java.rmi.RemoteException and its subclasses. */ protected boolean hasNonAppExceptions(Method m) { Class[] ex = m.getExceptionTypes(); for (int i = 0; i < ex.length; ++i) if (!java.rmi.RemoteException.class.isAssignableFrom(ex[i])) return false; return true; } /** * Analyze the fields of the class. * This will fill in the <code>fields</code> and <code>f_flags</code> * arrays. */ protected void analyzeFields() { //fields = cls.getFields(); fields = cls.getDeclaredFields(); f_flags = new byte[fields.length]; for (int i = 0; i < fields.length; ++i) { int mods = fields[i].getModifiers(); if (Modifier.isFinal(mods) && Modifier.isStatic(mods) && Modifier.isPublic(mods)) f_flags[i] |= F_CONSTANT; } } /** * Analyze the interfaces of the class. * This will fill in the <code>interfaces</code> array. */ protected void analyzeInterfaces() throws RMIIIOPViolationException { Class[] intfs = cls.getInterfaces(); ArrayList a = new ArrayList(); ArrayList b = new ArrayList(); for (int i = 0; i < intfs.length; ++i) { // Ignore java.rmi.Remote if (intfs[i] == java.rmi.Remote.class) continue; // Ignore java.io.Serializable if (intfs[i] == Serializable.class) continue; // Ignore java.io.Externalizable if (intfs[i] == Externalizable.class) continue; if (!RmiIdlUtil.isAbstractValueType(intfs[i])) { a.add(InterfaceAnalysis.getInterfaceAnalysis(intfs[i])); } else { b.add(ValueAnalysis.getValueAnalysis(intfs[i])); } } interfaces = new InterfaceAnalysis[a.size()]; interfaces = (InterfaceAnalysis[]) a.toArray(interfaces); abstractBaseValuetypes = new ValueAnalysis[b.size()]; abstractBaseValuetypes = (ValueAnalysis[]) b.toArray(abstractBaseValuetypes); } /** * Analyze the methods of the class. * This will fill in the <code>methods</code> and <code>m_flags</code> * arrays. */ protected void analyzeMethods() { // The dynamic stub and skeleton strategy generation mechanism // requires the inclusion of inherited methods in the analysis of // remote interfaces. To speed things up, inherited methods are // not considered in the analysis of a class or non-remote interface. if (cls.isInterface() && java.rmi.Remote.class.isAssignableFrom(cls)) methods = cls.getMethods(); else methods = cls.getDeclaredMethods(); m_flags = new byte[methods.length]; mutators = new int[methods.length]; // Find read-write properties for (int i = 0; i < methods.length; ++i) mutators[i] = -1; // no mutator here for (int i = 0; i < methods.length; ++i) { if (isAccessor(methods[i]) && (m_flags[i] & M_READ) == 0) { String attrName = attributeReadName(methods[i].getName()); Class iReturn = methods[i].getReturnType(); for (int j = i + 1; j < methods.length; ++j) { if (isMutator(methods[j]) && (m_flags[j] & M_WRITE) == 0 && attrName.equals(attributeWriteName(methods[j].getName()))) { Class[] jParams = methods[j].getParameterTypes(); if (jParams.length == 1 && jParams[0] == iReturn) { m_flags[i] |= M_READ; m_flags[j] |= M_WRITE; mutators[i] = j; break; } } } } else if (isMutator(methods[i]) && (m_flags[i] & M_WRITE) == 0) { String attrName = attributeWriteName(methods[i].getName()); Class[] iParams = methods[i].getParameterTypes(); for (int j = i + 1; j < methods.length; ++j) { if (isAccessor(methods[j]) && (m_flags[j] & M_READ) == 0 && attrName.equals(attributeReadName(methods[j].getName()))) { Class jReturn = methods[j].getReturnType(); if (iParams.length == 1 && iParams[0] == jReturn) { m_flags[i] |= M_WRITE; m_flags[j] |= M_READ; mutators[j] = i; break; } } } } } // Find read-only properties for (int i = 0; i < methods.length; ++i) if ((m_flags[i] & (M_READ | M_WRITE)) == 0 && isAccessor(methods[i])) m_flags[i] |= M_READONLY; // Check for overloaded and inherited methods for (int i = 0; i < methods.length; ++i) { if ((m_flags[i] & (M_READ | M_WRITE | M_READONLY)) == 0) { String iName = methods[i].getName(); for (int j = i + 1; j < methods.length; ++j) { if (iName.equals(methods[j].getName())) { m_flags[i] |= M_OVERLOADED; m_flags[j] |= M_OVERLOADED; } } } if (methods[i].getDeclaringClass() != cls) m_flags[i] |= M_INHERITED; } } /** * Convert an attribute read method name in Java format to * an attribute name in Java format. */ protected String attributeReadName(String name) { if (name.startsWith("get")) name = name.substring(3); else if (name.startsWith("is")) name = name.substring(2); else throw IIOPLogger.ROOT_LOGGER.notAnAccessor(name); return name; } /** * Convert an attribute write method name in Java format to * an attribute name in Java format. */ protected String attributeWriteName(String name) { if (name.startsWith("set")) name = name.substring(3); else throw IIOPLogger.ROOT_LOGGER.notAnAccessor(name); return name; } /** * Analyse constants. * This will fill in the <code>constants</code> array. */ protected void analyzeConstants() throws RMIIIOPViolationException { ArrayList a = new ArrayList(); for (int i = 0; i < fields.length; ++i) { if ((f_flags[i] & F_CONSTANT) == 0) continue; Class type = fields[i].getType(); // Only map primitives and java.lang.String if (!type.isPrimitive() && type != String.class) { // It is an RMI/IIOP violation for interfaces. if (cls.isInterface()) throw IIOPLogger.ROOT_LOGGER.badRMIIIOPConstantType(fields[i].getName(), cls.getName(), "1.2.3"); continue; } String name = fields[i].getName(); Object value; try { value = fields[i].get(null); } catch (Exception ex) { throw new RuntimeException(ex.toString()); } a.add(new ConstantAnalysis(name, type, value)); } constants = new ConstantAnalysis[a.size()]; constants = (ConstantAnalysis[]) a.toArray(constants); } /** * Analyse attributes. * This will fill in the <code>attributes</code> array. */ protected void analyzeAttributes() throws RMIIIOPViolationException { ArrayList a = new ArrayList(); for (int i = 0; i < methods.length; ++i) { //if ((m_flags[i]&M_INHERITED) != 0) // continue; if ((m_flags[i] & (M_READ | M_READONLY)) != 0) { // Read method of an attribute. String name = attributeReadName(methods[i].getName()); if ((m_flags[i] & M_READONLY) != 0) a.add(new AttributeAnalysis(name, methods[i])); else a.add(new AttributeAnalysis(name, methods[i], methods[mutators[i]])); } } attributes = new AttributeAnalysis[a.size()]; attributes = (AttributeAnalysis[]) a.toArray(attributes); } /** * Analyse operations. * This will fill in the <code>operations</code> array. * This implementation just creates an empty array; override * in subclasses for a real analysis. */ protected void analyzeOperations() throws RMIIIOPViolationException { operations = new OperationAnalysis[0]; } /** * Fixup overloaded operation names. * As specified in section 1.3.2.6. */ protected void fixupOverloadedOperationNames() throws RMIIIOPViolationException { for (int i = 0; i < methods.length; ++i) { if ((m_flags[i] & M_OVERLOADED) == 0) continue; // Find the operation OperationAnalysis oa = null; String javaName = methods[i].getName(); for (int opIdx = 0; oa == null && opIdx < operations.length; ++opIdx) if (operations[opIdx].getMethod().equals(methods[i])) oa = operations[opIdx]; if (oa == null) continue; // This method is not mapped. // Calculate new IDL name ParameterAnalysis[] params = oa.getParameters(); StringBuffer b = new StringBuffer(oa.getIDLName()); if (params.length == 0) b.append("__"); for (int j = 0; j < params.length; ++j) { String s = params[j].getTypeIDLName(); if (s.startsWith("::")) s = s.substring(2); if (s.startsWith("_")) { // remove leading underscore in IDL escaped identifier s = s.substring(1); } b.append('_'); while (!"".equals(s)) { int idx = s.indexOf("::"); b.append('_'); if (idx == -1) { b.append(s); s = ""; } else { b.append(s, 0, idx); if (s.length() > idx + 2 && s.charAt(idx + 2) == '_') { // remove leading underscore in IDL escaped identifier s = s.substring(idx + 3); } else { s = s.substring(idx + 2); } } } } // Set new IDL name oa.setIDLName(b.toString()); } } /** * Fixup names differing only in case. * As specified in section 1.3.2.7. */ protected void fixupCaseNames() throws RMIIIOPViolationException { ArrayList entries = getContainedEntries(); boolean[] clash = new boolean[entries.size()]; String[] upperNames = new String[entries.size()]; for (int i = 0; i < entries.size(); ++i) { AbstractAnalysis aa = (AbstractAnalysis) entries.get(i); clash[i] = false; upperNames[i] = aa.getIDLName().toUpperCase(Locale.ENGLISH); for (int j = 0; j < i; ++j) { if (upperNames[i].equals(upperNames[j])) { clash[i] = true; clash[j] = true; } } } for (int i = 0; i < entries.size(); ++i) { if (!clash[i]) continue; AbstractAnalysis aa = (AbstractAnalysis) entries.get(i); boolean noUpper = true; String name = aa.getIDLName(); StringBuffer b = new StringBuffer(name); b.append('_'); for (int j = 0; j < name.length(); ++j) { if (!Character.isUpperCase(name.charAt(j))) continue; if (noUpper) noUpper = false; else b.append('_'); b.append(j); } aa.setIDLName(b.toString()); } } /** * Return a list of all the entries contained here. * */ protected abstract ArrayList getContainedEntries(); /** * Return the class hash code, as specified in "The Common Object * Request Broker: Architecture and Specification" (01-02-33), * section 10.6.2. */ protected void calculateClassHashCode() { // The simple cases if (cls.isInterface()) classHashCode = 0; else if (!Serializable.class.isAssignableFrom(cls)) classHashCode = 0; else if (Externalizable.class.isAssignableFrom(cls)) classHashCode = 1; else // Go ask Util class for the hash code classHashCode = Util.getClassHashCode(cls); } /** * Escape non-ISO characters for an IR name. */ protected String escapeIRName(String name) { StringBuffer b = new StringBuffer(); for (int i = 0; i < name.length(); ++i) { char c = name.charAt(i); if (c < 256) b.append(c); else b.append("\\U").append(toHexString((int) c)); } return b.toString(); } /** * Return the IR global ID of the given class or interface. * This is described in section 1.3.5.7. * The returned string is in the RMI hashed format, like * "RMI:java.util.Hashtable:C03324C0EA357270:13BB0F25214AE4B8". */ protected void calculateRepositoryId() { if (cls.isArray() || cls.isPrimitive()) throw IIOPLogger.ROOT_LOGGER.notAnClassOrInterface(cls.getName()); if (cls.isInterface() && org.omg.CORBA.Object.class.isAssignableFrom(cls) && org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(cls)) { StringBuffer b = new StringBuffer("IDL:"); b.append(cls.getPackage().getName().replace('.', '/')); b.append('/'); String base = cls.getName(); base = base.substring(base.lastIndexOf('.') + 1); b.append(base).append(":1.0"); repositoryId = b.toString(); } else { StringBuffer b = new StringBuffer("RMI:"); b.append(escapeIRName(cls.getName())); memberPrefix = b.toString() + "."; String hashStr = toHexString(classHashCode); b.append(':').append(hashStr); ObjectStreamClass osClass = ObjectStreamClass.lookup(cls); if (osClass != null) { long serialVersionUID = osClass.getSerialVersionUID(); String SVUID = toHexString(serialVersionUID); if (classHashCode != serialVersionUID) b.append(':').append(SVUID); memberPostfix = ":" + hashStr + ":" + SVUID; } else memberPostfix = ":" + hashStr; repositoryId = b.toString(); } } }
24,725
31.153446
117
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/marshal/CDRStream.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.marshal; import java.io.Externalizable; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.rmi.CORBA.Util; import javax.rmi.PortableRemoteObject; import org.omg.CORBA.portable.IDLEntity; import org.omg.CORBA_2_3.portable.InputStream; import org.omg.CORBA_2_3.portable.OutputStream; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.rmi.RmiIdlUtil; /** * Utility class with static methods to: * <ul> * <li>get the <code>CDRStreamReader</code> for a given class</li> * <li>get the <code>CDRStreamWriter</code> for a given class</li> * </ul> * <p/> * The <code>CDRStreamReader</code>s and <code>CDRStreamWriter</code>s * returned by these methods are instances of static inner classes * defined by <code>CDRStream</code>. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> */ public class CDRStream { /** * Returns the abbreviated name of the marshaller for given * <code>Class</code>. * <p/> * <p>Abbreviated names of marshallers for basic types follow the usual * Java convention: * <br> * <pre> * type abbrev name * boolean "Z" * byte "B" * char "C" * double "D" * float "F" * int "I" * long "J" * short "S" * void "V" * </pre> * <p/> * <p>The abbreviated names of marshallers for object types are: * <br> * <pre> * java.lang.String "G" (strinG) * RMI remote interface "R" + interfaceName * RMI abstract interface "A" * serializable "E" (sErializablE) * valuetype "L" + className * externalizable "X" (eXternalizable) * org.omg.CORBA.Object "M" (oMg) * IDL interface "N" + interfaceName * java.lang.Object "O" * </pre> * <p/> * <p>As an example: the abbreviated name of a marshaller for a valuetype * class named <code>Foo</code> is the string <code>"LFoo"</code>. */ public static String abbrevFor(Class clz) { if (clz == Boolean.TYPE) { return "Z"; } else if (clz == Byte.TYPE) { return "B"; } else if (clz == Character.TYPE) { return "C"; } else if (clz == Double.TYPE) { return "D"; } else if (clz == Float.TYPE) { return "F"; } else if (clz == Integer.TYPE) { return "I"; } else if (clz == Long.TYPE) { return "J"; } else if (clz == Short.TYPE) { return "S"; } else if (clz == Void.TYPE) { return "V"; } else if (clz == String.class) { return "G"; // strinG } else if (RmiIdlUtil.isRMIIDLRemoteInterface(clz)) { return "R" + clz.getName(); // Remote interface } else if (clz == org.omg.CORBA.Object.class) { return "M"; // oMg (CORBA Object) } else if (org.omg.CORBA.Object.class.isAssignableFrom(clz)) { return "N" + clz.getName(); // IDL iNterface } else if (IDLEntity.class.isAssignableFrom(clz)) { return "L" + clz.getName(); // vaLuetype } else if (clz == Serializable.class) { return "E"; // sErializablE } else if (RmiIdlUtil.isAbstractInterface(clz)) { return "A"; // Abstract interface } else if (Serializable.class.isAssignableFrom(clz)) { return "L" + clz.getName(); // vaLuetype } else if (Externalizable.class.isAssignableFrom(clz)) { return "X"; // eXternalizable } else if (clz == Object.class) { return "O"; // Object } else { return "L" + clz.getName(); // vaLuetype } } /** * Returns a <code>CDRStreamReader</code> given an abbreviated name * and a <code>ClassLoader</code> for valuetype classes. */ public static CDRStreamReader readerFor(String s, ClassLoader cl) { switch (s.charAt(0)) { case 'A': return AbstractInterfaceReader.instance; case 'B': return ByteReader.instance; case 'C': return CharReader.instance; case 'D': return DoubleReader.instance; case 'E': return SerializableReader.instance; case 'F': return FloatReader.instance; case 'G': return StringReader.instance; case 'I': return IntReader.instance; case 'J': return LongReader.instance; case 'L': try { // Use Class.forName() (rather than cl.loadClass()), because // Class.forName() loads Java array types (which are valuetypes). return new ValuetypeReader(Class.forName(s.substring(1), true, cl)); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(s.substring(1), e); } case 'M': return CorbaObjectReader.instance; case 'N': try { return new IdlInterfaceReader(cl.loadClass(s.substring(1))); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(s.substring(1), e); } case 'O': return ObjectReader.instance; case 'R': try { return new RemoteReader(cl.loadClass(s.substring(1))); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(s.substring(1), e); } case 'S': return ShortReader.instance; case 'V': return null; case 'X': return ExternalizableReader.instance; case 'Z': return BooleanReader.instance; default: return null; } } /** * Returns a <code>CDRStreamWriter</code> given an abbreviated name * and a <code>ClassLoader</code> for valuetype classes. */ public static CDRStreamWriter writerFor(String s, ClassLoader cl) { switch (s.charAt(0)) { case 'A': return AbstractInterfaceWriter.instance; case 'B': return ByteWriter.instance; case 'C': return CharWriter.instance; case 'D': return DoubleWriter.instance; case 'E': return SerializableWriter.instance; case 'F': return FloatWriter.instance; case 'G': return StringWriter.instance; case 'I': return IntWriter.instance; case 'J': return LongWriter.instance; case 'L': try { // Use Class.forName() (rather than cl.loadClass()), because // Class.forName() loads Java array types (which are valuetypes). return new ValuetypeWriter(Class.forName(s.substring(1), true, cl)); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(s.substring(1), e); } case 'M': return CorbaObjectWriter.instance; case 'N': try { return new IdlInterfaceWriter(cl.loadClass(s.substring(1))); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(s.substring(1), e); } case 'O': return ObjectWriter.instance; case 'R': return RemoteWriter.instance; case 'S': return ShortWriter.instance; case 'V': return null; case 'X': return ExternalizableWriter.instance; case 'Z': return BooleanWriter.instance; default: return null; } } /** * Returns the <code>CDRStreamReader</code> for a given <code>Class</code>. */ public static CDRStreamReader readerFor(Class clz) { if (clz == Boolean.TYPE) { return BooleanReader.instance; } else if (clz == Byte.TYPE) { return ByteReader.instance; } else if (clz == Character.TYPE) { return CharReader.instance; } else if (clz == Double.TYPE) { return DoubleReader.instance; } else if (clz == Float.TYPE) { return FloatReader.instance; } else if (clz == Integer.TYPE) { return IntReader.instance; } else if (clz == Long.TYPE) { return LongReader.instance; } else if (clz == Short.TYPE) { return ShortReader.instance; } else if (clz == Void.TYPE) { return null; } else if (clz == String.class) { return StringReader.instance; } else if (RmiIdlUtil.isRMIIDLRemoteInterface(clz)) { return new RemoteReader(clz); } else if (clz == org.omg.CORBA.Object.class) { return CorbaObjectReader.instance; } else if (org.omg.CORBA.Object.class.isAssignableFrom(clz)) { return new IdlInterfaceReader(clz); } else if (IDLEntity.class.isAssignableFrom(clz)) { return new ValuetypeReader(clz); } else if (clz == Serializable.class) { return SerializableReader.instance; } else if (RmiIdlUtil.isAbstractInterface(clz)) { return AbstractInterfaceReader.instance; } else if (Serializable.class.isAssignableFrom(clz)) { return new ValuetypeReader(clz); } else if (Externalizable.class.isAssignableFrom(clz)) { return ExternalizableReader.instance; } else if (clz == Object.class) { return ObjectReader.instance; } else { return new ValuetypeReader(clz); } } /** * Returns the <code>CDRStreamWriter</code> for a given <code>Class</code>. */ public static CDRStreamWriter writerFor(Class clz) { if (clz == Boolean.TYPE) { return BooleanWriter.instance; } else if (clz == Byte.TYPE) { return ByteWriter.instance; } else if (clz == Character.TYPE) { return CharWriter.instance; } else if (clz == Double.TYPE) { return DoubleWriter.instance; } else if (clz == Float.TYPE) { return FloatWriter.instance; } else if (clz == Integer.TYPE) { return IntWriter.instance; } else if (clz == Long.TYPE) { return LongWriter.instance; } else if (clz == Short.TYPE) { return ShortWriter.instance; } else if (clz == String.class) { return StringWriter.instance; } else if (clz == Void.TYPE) { return null; } else if (RmiIdlUtil.isRMIIDLRemoteInterface(clz)) { return RemoteWriter.instance; } else if (clz == org.omg.CORBA.Object.class) { return CorbaObjectWriter.instance; } else if (org.omg.CORBA.Object.class.isAssignableFrom(clz)) { return new IdlInterfaceWriter(clz); } else if (IDLEntity.class.isAssignableFrom(clz)) { return new ValuetypeWriter(clz); } else if (clz == Serializable.class) { return SerializableWriter.instance; } else if (RmiIdlUtil.isAbstractInterface(clz)) { return AbstractInterfaceWriter.instance; } else if (Serializable.class.isAssignableFrom(clz)) { return new ValuetypeWriter(clz); } else if (Externalizable.class.isAssignableFrom(clz)) { return ExternalizableWriter.instance; } else if (clz == Object.class) { return ObjectWriter.instance; } else { return new ValuetypeWriter(clz); } } // Private ----------------------------------------------------------------- // Static inner classes (all of them private) ------------------------------ /** * Singleton class that unmarshals <code>boolean</code>s from a CDR input * stream. */ private static final class BooleanReader implements CDRStreamReader { static final CDRStreamReader instance = new BooleanReader(); private BooleanReader() { } public Object read(InputStream in) { return in.read_boolean(); } } /** * Singleton class that unmarshals <code>byte</code>s from a CDR input * stream. */ private static final class ByteReader implements CDRStreamReader { static final CDRStreamReader instance = new ByteReader(); private ByteReader() { } public Object read(InputStream in) { return in.read_octet(); } } /** * Singleton class that unmarshals <code>char</code>s from a CDR input * stream. */ private static final class CharReader implements CDRStreamReader { static final CDRStreamReader instance = new CharReader(); private CharReader() { } public Object read(InputStream in) { return in.read_wchar(); } } /** * Singleton class that unmarshals <code>double</code>s from a CDR input * stream. */ private static final class DoubleReader implements CDRStreamReader { static final CDRStreamReader instance = new DoubleReader(); private DoubleReader() { } public Object read(InputStream in) { return in.read_double(); } } /** * Singleton class that unmarshals <code>float</code>s from a CDR input * stream. */ private static final class FloatReader implements CDRStreamReader { static final CDRStreamReader instance = new FloatReader(); private FloatReader() { } public Object read(InputStream in) { return in.read_float(); } } /** * Singleton class that unmarshals <code>int</code>s from a CDR input * stream. */ private static final class IntReader implements CDRStreamReader { static final CDRStreamReader instance = new IntReader(); private IntReader() { } public Object read(InputStream in) { return in.read_long(); } } /** * Singleton class that unmarshals <code>long</code>s from a CDR input * stream. */ private static final class LongReader implements CDRStreamReader { static final CDRStreamReader instance = new LongReader(); private LongReader() { } public Object read(InputStream in) { return in.read_longlong(); } } /** * Singleton class that unmarshals <code>short</code>s from a CDR input * stream. */ private static final class ShortReader implements CDRStreamReader { static final CDRStreamReader instance = new ShortReader(); private ShortReader() { } public Object read(InputStream in) { return in.read_short(); } } /** * Singleton class that unmarshals <code>String</code>s from a CDR input * stream. */ private static final class StringReader implements CDRStreamReader { static final CDRStreamReader instance = new StringReader(); private StringReader() { } public Object read(InputStream in) { return in.read_value(String.class); } } /** * Class that unmarshals <code>java.rmi.Remote</code> objects from a CDR * input stream. A <code>RemoteReader</code> is specific for a given * remote interface, which is passed as a parameter to the * <code>RemoteReader</code> constructor. */ private static final class RemoteReader implements CDRStreamReader { private Class clz; RemoteReader(Class clz) { this.clz = clz; } public Object read(InputStream in) { // The narrow() call downloads the stub from the codebase embedded // within the IOR of the unmarshalled object. return PortableRemoteObject.narrow(in.read_Object(), clz); } } /** * Singleton class that unmarshals objects whose declared type is * <code>java.lang.Object</code> from a CDR input stream. */ private static final class ObjectReader implements CDRStreamReader { static final CDRStreamReader instance = new ObjectReader(); private ObjectReader() { } public Object read(InputStream in) { return Util.readAny(in); } } /** * Singleton class that unmarshals objects whose declared type is * <code>java.io.Serializable</code> from a CDR input stream. */ private static final class SerializableReader implements CDRStreamReader { static final CDRStreamReader instance = new SerializableReader(); private SerializableReader() { } public Object read(InputStream in) { return (Serializable) Util.readAny(in); } } /** * Singleton class that unmarshals objects whose declared type is * <code>java.io.Externalizable</code> from a CDR input stream. */ private static final class ExternalizableReader implements CDRStreamReader { static final CDRStreamReader instance = new ExternalizableReader(); private ExternalizableReader() { } public Object read(InputStream in) { return (Externalizable) Util.readAny(in); } } /** * Singleton class that unmarshals objects whose declared type is * <code>org.omg.CORBA.Object</code> from a CDR input stream. */ private static final class CorbaObjectReader implements CDRStreamReader { static final CDRStreamReader instance = new CorbaObjectReader(); private CorbaObjectReader() { } public Object read(InputStream in) { return (org.omg.CORBA.Object) in.read_Object(); } } /** * Class that unmarshals IDL interfaces from a CDR input stream. * An <code>IdlInterfaceReader</code> is specific for objects that * implement the Java interface passed as a parameter to the * <code>IdlInterfaceReader</code> constructor. This Java interface * must extend <code>org.omg.CORBA.Object</code>. */ private static final class IdlInterfaceReader implements CDRStreamReader { private static Class[] paramTypes = {org.omg.CORBA.portable.InputStream.class}; // The readMethod for this IdlInterfaceReader. private Method readMethod = null; IdlInterfaceReader(Class clz) { String helperClassName = clz.getName() + "Helper"; try { Class helperClass = clz.getClassLoader().loadClass(helperClassName); readMethod = helperClass.getMethod("read", paramTypes); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(helperClassName, e); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noReadMethodInHelper(helperClassName, e); } } public Object read(InputStream in) { try { return readMethod.invoke(null, new Object[]{in}); } catch (IllegalAccessException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (InvocationTargetException e) { throw IIOPLogger.ROOT_LOGGER.errorUnmarshaling(org.omg.CORBA.Object.class, e.getTargetException()); } } } /** * Singleton class that unmarshals from a CDR output stream objects whose * declared type is an interface that does not extend * <code>java.rmi.Remote</code> and whose declared methods * (including inherited ones) all throw * <code>java.rmi.RemoteException</code>. */ private static final class AbstractInterfaceReader implements CDRStreamReader { static final CDRStreamReader instance = new AbstractInterfaceReader(); private AbstractInterfaceReader() { } public Object read(InputStream in) { return in.read_abstract_interface(); } } /** * Class that unmarshals valuetypes from a CDR input stream. * A <code>ValuetypeReader</code> is specific for objects of a given class, * which is passed as a parameter to the <code>ValuetypeReader</code> * constructor and must implement <code>java.io.Serializable</code>. */ private static final class ValuetypeReader implements CDRStreamReader { private Class clz; ValuetypeReader(Class clz) { this.clz = clz; } public Object read(InputStream in) { return in.read_value(clz); } } /** * Singleton class that marshals <code>boolean</code>s into a CDR output * stream. */ private static final class BooleanWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new BooleanWriter(); private BooleanWriter() { } public void write(OutputStream out, Object obj) { out.write_boolean((Boolean) obj); } } /** * Singleton class that marshals <code>byte</code>s into a CDR output * stream. */ private static final class ByteWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new ByteWriter(); private ByteWriter() { } public void write(OutputStream out, Object obj) { out.write_octet((Byte) obj); } } /** * Singleton class that marshals <code>char</code>s into a CDR output * stream. */ private static final class CharWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new CharWriter(); private CharWriter() { } public void write(OutputStream out, Object obj) { out.write_wchar((Character) obj); } } /** * Singleton class that marshals <code>double</code>s into a CDR output * stream. */ private static final class DoubleWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new DoubleWriter(); private DoubleWriter() { } public void write(OutputStream out, Object obj) { out.write_double((Double) obj); } } /** * Singleton class that marshals <code>float</code>s into a CDR output * stream. */ private static final class FloatWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new FloatWriter(); private FloatWriter() { } public void write(OutputStream out, Object obj) { out.write_float((Float) obj); } } /** * Singleton class that marshals <code>int</code>s into a CDR output * stream. */ private static final class IntWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new IntWriter(); private IntWriter() { } public void write(OutputStream out, Object obj) { out.write_long((Integer) obj); } } /** * Singleton class that marshals <code>long</code>s into a CDR output * stream. */ private static final class LongWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new LongWriter(); private LongWriter() { } public void write(OutputStream out, Object obj) { out.write_longlong((Long) obj); } } /** * Singleton class that marshals <code>short</code>s into a CDR output * stream. */ private static final class ShortWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new ShortWriter(); private ShortWriter() { } public void write(OutputStream out, Object obj) { out.write_short((Short) obj); } } /** * Singleton class that marshals <code>String</code>s into a CDR output * stream. */ private static final class StringWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new StringWriter(); private StringWriter() { } public void write(OutputStream out, Object obj) { out.write_value((String) obj, String.class); } } /** * Singleton class that marshals <code>java.rmi.Remote</code> objects into * a CDR output stream. */ private static final class RemoteWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new RemoteWriter(); private RemoteWriter() { } public void write(OutputStream out, Object obj) { out.write_Object((org.omg.CORBA.Object) obj); } } /** * Singleton class that marshals objects whose declared type is * <code>java.lang.Object</code> into a CDR output stream. */ private static final class ObjectWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new ObjectWriter(); private ObjectWriter() { } public void write(OutputStream out, Object obj) { Util.writeAny(out, obj); } } /** * Singleton class that marshals objects whose declared type is * <code>java.io.Serializable</code> into a CDR output stream. */ private static final class SerializableWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new SerializableWriter(); private SerializableWriter() { } public void write(OutputStream out, Object obj) { Util.writeAny(out, (Serializable) obj); } } /** * Singleton class that marshals objects whose declared type is * <code>java.io.Externalizable</code> into a CDR output stream. */ private static final class ExternalizableWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new ExternalizableWriter(); private ExternalizableWriter() { } public void write(OutputStream out, Object obj) { Util.writeAny(out, (Externalizable) obj); } } /** * Singleton class that marshals objects whose declared type is * <code>org.omg.CORBA.Object</code> into a CDR output stream. */ private static final class CorbaObjectWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new CorbaObjectWriter(); private CorbaObjectWriter() { } public void write(OutputStream out, Object obj) { out.write_Object((org.omg.CORBA.Object) obj); } } /** * Class that marshals IDL interfaces into a CDR output stream. * An <code>IdlInterfaceWriter</code> is specific for objects that * implement the Java interface is passed as a parameter to the * <code>IdlInterfaceWriter</code> constructor. This Java interface * must extend <code>org.omg.CORBA.Object</code>. */ private static final class IdlInterfaceWriter implements CDRStreamWriter { // The writeMethod for this IdlInterfaceReader. private Method writeMethod = null; IdlInterfaceWriter(Class clz) { String helperClassName = clz.getName() + "Helper"; try { Class helperClass = clz.getClassLoader().loadClass(helperClassName); Class[] paramTypes = { org.omg.CORBA.portable.OutputStream.class, clz }; writeMethod = helperClass.getMethod("write", paramTypes); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(helperClassName, e); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noWriteMethodInHelper(helperClassName, e); } } public void write(OutputStream out, Object obj) { try { writeMethod.invoke(null, new Object[]{out, obj}); } catch (IllegalAccessException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (InvocationTargetException e) { throw IIOPLogger.ROOT_LOGGER.errorMarshaling(org.omg.CORBA.Object.class, e.getTargetException()); } } } /** * Singleton class that marshals into a CDR output stream objects whose * declared type is an interface that does not extend * <code>java.rmi.Remote</code> and whose declared methods * (including inherited ones) all throw * <code>java.rmi.RemoteException</code>. */ private static final class AbstractInterfaceWriter implements CDRStreamWriter { static final CDRStreamWriter instance = new AbstractInterfaceWriter(); private AbstractInterfaceWriter() { } public void write(OutputStream out, Object obj) { out.write_abstract_interface(obj); } } /** * Class that marshals valuetypes into a CDR output stream. * A <code>ValuetypeWriter</code> is specific for objects of a given class, * which is passed as a parameter to the <code>ValuetypeWriter</code> * constructor and must implement <code>java.io.Serializable</code>. */ private static final class ValuetypeWriter implements CDRStreamWriter { private Class clz; ValuetypeWriter(Class clz) { this.clz = clz; } public void write(OutputStream out, Object obj) { out.write_value((Serializable) obj, clz); } } }
32,293
32.430642
115
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/marshal/CDRStreamReader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.marshal; import org.omg.CORBA_2_3.portable.InputStream; /** * Interface of an object that knows how to unmarshal a Java basic type or * object from a CDR input stream. Implementations of this interface are * specialized for particular types: an <code>IntReader</code> is a * <code>CDRStreamReader</code> that knows how to unmarshal <code>int</code>s, * a <code>LongReader</code> is a <code>CDRStreamReader</code> that knows how * to unmarshal <code>long</code>s, and so on. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @version $Revision: 81018 $ */ public interface CDRStreamReader { /** * Unmarshals a Java basic data type or object from a CDR input stream. * * @param in the input stream * @return a basic data type (within a suitable wrapper instance) or * object unmarshalled from the stream */ Object read(InputStream in); }
1,987
41.297872
78
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/marshal/CDRStreamWriter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.marshal; import org.omg.CORBA_2_3.portable.OutputStream; /** * Interface of an object that knows how to marshal a Java basic type or * object into a CDR input stream. Implementations of this interface are * specialized for particular types: an <code>IntWriter</code> is a * <code>CDRStreamWriter</code> that knows how to marshal <code>int</code>s, * a <code>LongWriter</code> is a <code>CDRStreamWriter</code> that knows how * to marshal <code>long</code>s, and so on. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @version $Revision: 81018 $ */ public interface CDRStreamWriter { /** * Marshals a Java basic data type or object into a CDR output stream. * * @param out the output stream * @param obj the basic data type (within a suitable wrapper instance) * or object to be marshalled */ void write(OutputStream out, Object obj); }
1,992
41.404255
77
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/marshal/strategy/StubStrategy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.marshal.strategy; import java.rmi.NoSuchObjectException; import java.rmi.Remote; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.rmi.UnexpectedException; import javax.rmi.PortableRemoteObject; import org.omg.CORBA.UserException; import org.omg.CORBA.portable.IDLEntity; import org.omg.CORBA_2_3.portable.InputStream; import org.omg.CORBA_2_3.portable.OutputStream; import org.jboss.javax.rmi.RemoteObjectSubstitutionManager; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStream; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStreamReader; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStreamWriter; import org.wildfly.security.manager.WildFlySecurityManager; /** * An <code>StubStrategy</code> for a given method knows how to marshal * the sequence of method parameters into a CDR output stream, how to unmarshal * from a CDR input stream the return value of the method, and how to unmarshal * from a CDR input stream an application exception thrown by the method. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @version $Revision: 81018 $ */ public class StubStrategy { /** * Each <code>CDRStreamWriter</code> in the array marshals a method * parameter. */ private CDRStreamWriter[] paramWriters; /** * List of exception classes. */ private List<Class<?>> exceptionList; /** * Maps exception repository ids into ExceptionReader instances. */ private Map<String, ExceptionReader> exceptionMap; /** * A <code>CDRStreamReader</code> that unmarshals the return value of the * method. */ private CDRStreamReader retvalReader; /** * If this <code>StubStrategy</code> is for a method that returns a * remote interface, this field contains the remote interface's * <code>Class</code>. Otherwise it contains null. */ private Class<?> retvalRemoteInterface; /** * Returns an <code>StubStrategy</code> for a method, given descriptions * of the method parameters, exceptions, and return value. Parameter and * return value descriptions are "marshaller abbreviated names". * * @param paramTypes a string array with marshaller abbreviated names for * the method parameters * @param excepIds a string array with the CORBA repository ids of the * exceptions thrown by the method * @param excepTypes a string array with the Java class names of the * exceptions thrown by the method * @param retvalType marshaller abbreaviated name for the return value of * the method * @param cl a <code>ClassLoader</code> to load value classes * (if null, the current thread's context class loader * will be used) * @return an <code>StubStrategy</code> for the operation with the * parameters, exceptions, and return value specified. * @see CDRStream#abbrevFor(Class clz) */ public static StubStrategy forMethod(String[] paramTypes, String[] excepIds, String[] excepTypes, String retvalType, ClassLoader cl) { // This "factory method" exists just because I have found it easier // to invoke a static method (rather than invoking operator new) // from a stub class dynamically assembled by an instance of // org.jboss.proxy.ProxyAssembler. return new StubStrategy(paramTypes, excepIds, excepTypes, retvalType, cl); } /** * Constructs an <code>StubStrategy</code> for a method, given * descriptions of the method parameters, exceptions, and return value. * Parameter and return value descriptions are "marshaller abbreviated * names". * * @param paramTypes a string array with marshaller abbreviated names for * the method parameters * @param excepIds a string array with the CORBA repository ids of the * exceptions thrown by the method * @param excepTypes a string array with the Java class names of the * exceptions thrown by the method * @param retvalType marshaller abbreaviated name for the return value of * the method * @param cl a <code>ClassLoader</code> to load value classes * (if null, the current thread's context class loader * will be used) * @see CDRStream#abbrevFor(Class clz) */ private StubStrategy(String[] paramTypes, String[] excepIds, String[] excepTypes, String retvalType, ClassLoader cl) { if (cl == null) { cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); } // Initialize paramWriters int len = paramTypes.length; paramWriters = new CDRStreamWriter[len]; for (int i = 0; i < len; i++) { paramWriters[i] = CDRStream.writerFor(paramTypes[i], cl); } // Initialize exception list and exception map exceptionList = new ArrayList<Class<?>>(); exceptionMap = new HashMap<String, ExceptionReader>(); len = excepIds.length; for (int i = 0; i < len; i++) { try { Class<?> clz = cl.loadClass(excepTypes[i]); exceptionList.add(clz); ExceptionReader exceptionReader = new ExceptionReader(clz, excepIds[i]); exceptionMap.put(exceptionReader.getReposId(), exceptionReader); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(excepTypes[i], e); } } // Initialize retvalReader retvalReader = CDRStream.readerFor(retvalType, cl); // Initialize retvalRemoteInterface if (retvalType.charAt(0) == 'R') { try { retvalRemoteInterface = cl.loadClass(retvalType.substring(1)); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(retvalType.substring(1), e); } } } /** * Marshals the sequence of method parameters into an output stream. * * @param out a CDR output stream * @param params an object array with the parameters. */ public void writeParams(OutputStream out, Object[] params) { int len = params.length; if (len != paramWriters.length) { throw IIOPLogger.ROOT_LOGGER.errorMashalingParams(); } for (int i = 0; i < len; i++) { Object param = params[i]; if (param instanceof PortableRemoteObject) { try { param = PortableRemoteObject.toStub((Remote) param); } catch (NoSuchObjectException e) { throw new RuntimeException(e); } } paramWriters[i].write(out, RemoteObjectSubstitutionManager.writeReplaceRemote(param)); } } /** * Returns true if this <code>StubStrategy</code>'s method is non void. */ public boolean isNonVoid() { return (retvalReader != null); } /** * Unmarshals from an input stream the return value of the method. * * @param in a CDR input stream * @return a value unmarshaled from the stream. */ public Object readRetval(InputStream in) { return retvalReader.read(in); } /** * Unmarshals from an input stream an exception thrown by the method. * * @param id the repository id of the exception to unmarshal * @param in a CDR input stream * @return an exception unmarshaled from the stream. */ public Exception readException(String id, InputStream in) { ExceptionReader exceptionReader = (ExceptionReader) exceptionMap.get(id); if (exceptionReader == null) { return new UnexpectedException(id); } else { return exceptionReader.read(in); } } /** * Checks if a given <code>Throwable</code> instance corresponds to an * exception declared by this <code>StubStrategy</code>'s method. * * @param t an exception class * @return true if <code>t</code> is an instance of any of the * exceptions declared by this <code>StubStrategy</code>'s * method, false otherwise. */ public boolean isDeclaredException(Throwable t) { Iterator<Class<?>> iterator = exceptionList.iterator(); while (iterator.hasNext()) { if (((Class<?>) iterator.next()).isInstance(t)) { return true; } } return false; } /** * Converts the return value of a local invocation into the expected type. * A conversion is needed if the return value is a remote interface * (in this case <code>PortableRemoteObject.narrow()</code> must be called). * * @param obj the return value to be converted * @return the converted value. */ public Object convertLocalRetval(Object obj) { if (retvalRemoteInterface == null) return obj; else return PortableRemoteObject.narrow(obj, retvalRemoteInterface); } // Static inner class (private) -------------------------------------------- /** * An <code>ExceptionReader</code> knows how to read exceptions of a given * class from a CDR input stream. */ private static class ExceptionReader { /** * The exception class. */ private Class<?> clz; /** * The CORBA repository id of the exception class. */ private String reposId; /* * If the exception class corresponds to an IDL-defined exception, this * field contains the read method of the associated helper class. * A null value indicates that the exception class does not correspond * to an IDL-defined exception. */ private java.lang.reflect.Method readMethod = null; /** * Constructs an <code>ExceptionReader</code> for a given exception * class. */ ExceptionReader(Class<?> clz, String reposId) { this.clz = clz; if (IDLEntity.class.isAssignableFrom(clz) && UserException.class.isAssignableFrom(clz)) { // This ExceptionReader corresponds to an IDL-defined exception String helperClassName = clz.getName() + "Helper"; try { Class<?> helperClass = clz.getClassLoader().loadClass(helperClassName); Class<?>[] paramTypes = {org.omg.CORBA.portable.InputStream.class}; readMethod = helperClass.getMethod("read", paramTypes); // Ignore the reposId parameter and use the id // returned by the IDL-generated helper class java.lang.reflect.Method idMethod = helperClass.getMethod("id", (Class[])null); this.reposId = (String) idMethod.invoke(null, (Object[])null); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(helperClassName, e); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noReadMethodInHelper(helperClassName, e); } catch (IllegalAccessException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (java.lang.reflect.InvocationTargetException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e.getTargetException()); } } else { // This ExceptionReader does not correspond to an IDL-defined // exception: store the reposId parameter this.reposId = reposId; } } public String getReposId() { return reposId; } /** * Reads an exception from a CDR input stream. */ public Exception read(InputStream in) { if (readMethod != null) { try { return (Exception) readMethod.invoke(null, new Object[]{in}); } catch (IllegalAccessException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (java.lang.reflect.InvocationTargetException e) { throw IIOPLogger.ROOT_LOGGER.errorUnmarshaling(IDLEntity.class, e.getTargetException()); } } else { in.read_string(); // read and discard the repository id return (Exception) in.read_value(clz); } } } // end of inner class ExceptionReader }
14,326
38.686981
108
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/marshal/strategy/SkeletonStrategy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.marshal.strategy; import java.lang.reflect.Method; import java.rmi.RemoteException; import org.omg.CORBA.UserException; import org.omg.CORBA.portable.IDLEntity; import org.omg.CORBA.portable.UnknownException; import org.omg.CORBA_2_3.portable.InputStream; import org.omg.CORBA_2_3.portable.OutputStream; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.rmi.ExceptionAnalysis; import org.wildfly.iiop.openjdk.rmi.RMIIIOPViolationException; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStream; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStreamReader; import org.wildfly.iiop.openjdk.rmi.marshal.CDRStreamWriter; import org.jboss.javax.rmi.RemoteObjectSubstitutionManager; /** * A <code>SkeletonStrategy</code> for a given method knows how to * unmarshalthe sequence of method parameters from a CDR input stream, how to * marshal into a CDR output stream the return value of the method, and how to * marshal into a CDR output stream any exception thrown by the method. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @version $Revision: 81018 $ */ public class SkeletonStrategy { /** * Each <code>CDRStreamReader</code> in the array unmarshals a method * parameter. */ private final CDRStreamReader[] paramReaders; /** * A <code>Method</code> instance. */ private final Method m; /** * Each <code>ExceptionWriter</code> in the array knows how to marshal * an exception that may be thrown be the method. The array is sorted so * that no writer for a derived exception appears after the base * exception writer. */ private final ExceptionWriter[] excepWriters; /** * A <code>CDRStreamWriter</code> that marshals the return value of the * method. */ private final CDRStreamWriter retvalWriter; // Public ----------------------------------------------------------------- /* * Constructs a <code>SkeletonStrategy</code> for a given method. */ public SkeletonStrategy(final Method m) { // Keep the method this.m = m; // Initialize paramReaders Class[] paramTypes = m.getParameterTypes(); int len = paramTypes.length; paramReaders = new CDRStreamReader[len]; for (int i = 0; i < len; i++) { paramReaders[i] = CDRStream.readerFor(paramTypes[i]); } // Initialize excepWriters Class[] excepTypes = m.getExceptionTypes(); len = excepTypes.length; int n = 0; for (int i = 0; i < len; i++) { if (!RemoteException.class.isAssignableFrom(excepTypes[i])) { n++; } } excepWriters = new ExceptionWriter[n]; int j = 0; for (int i = 0; i < len; i++) { if (!RemoteException.class.isAssignableFrom(excepTypes[i])) { excepWriters[j++] = new ExceptionWriter(excepTypes[i]); } } ExceptionWriter.arraysort(excepWriters); // Initialize retvalWriter retvalWriter = CDRStream.writerFor(m.getReturnType()); } /** * Unmarshals the sequence of method parameters from an input stream. * * @param in a CDR input stream * @return an object array with the parameters. */ public Object[] readParams(InputStream in) { int len = paramReaders.length; Object[] params = new Object[len]; for (int i = 0; i < len; i++) { params[i] = paramReaders[i].read(in); } return params; } /** * Returns this <code>SkeletonStrategy</code>'s method. */ public Method getMethod() { return m; } /** * Returns true if this <code>SkeletonStrategy</code>'s method * is non void. */ public boolean isNonVoid() { return (retvalWriter != null); } /** * Marshals into an output stream the return value of the method. * * @param out a CDR output stream * @param retVal the value to be written. */ public void writeRetval(OutputStream out, Object retVal) { retvalWriter.write(out, RemoteObjectSubstitutionManager.writeReplaceRemote(retVal)); } /** * Marshals into an output stream an exception thrown by the method. * * @param out a CDR output stream * @param e the exception to be written. */ public void writeException(OutputStream out, Throwable e) { int len = excepWriters.length; for (int i = 0; i < len; i++) { if (excepWriters[i].getExceptionClass().isInstance(e)) { excepWriters[i].write(out, e); return; } } throw new UnknownException(e); } // Static inner class (private) -------------------------------------------- /** * An <code>ExceptionWriter</code> knows how to write exceptions of a given * class to a CDR output stream. */ private static class ExceptionWriter implements CDRStreamWriter { /** * The exception class. */ private Class clz; /* * If the exception class corresponds to an IDL-defined exception, this * field contains the write method of the associated helper class. * A null value indicates that the exception class does not correspond * to an IDL-defined exception. */ private Method writeMethod = null; /** * The CORBA repository id of the exception class. (This field is used * if the exception class does not correspond to an IDL-defined * exception. An IDL-generated helper class provides the repository id * of an IDL-defined exception.) */ private String reposId; /** * Constructs an <code>ExceptionWriter</code> for a given exception * class. */ ExceptionWriter(Class clz) { this.clz = clz; if (IDLEntity.class.isAssignableFrom(clz) && UserException.class.isAssignableFrom(clz)) { // This ExceptionWriter corresponds to an IDL-defined exception String helperClassName = clz.getName() + "Helper"; try { Class helperClass = clz.getClassLoader().loadClass(helperClassName); Class[] paramTypes = {org.omg.CORBA.portable.OutputStream.class, clz}; writeMethod = helperClass.getMethod("write", paramTypes); } catch (ClassNotFoundException e) { throw IIOPLogger.ROOT_LOGGER.errorLoadingClass(helperClassName, e); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noWriteMethodInHelper(helperClassName, e); } } else { // This ExceptionWriter does not correspond to an IDL-defined // exception try { this.reposId = ExceptionAnalysis.getExceptionAnalysis(clz) .getExceptionRepositoryId(); } catch (RMIIIOPViolationException e) { throw IIOPLogger.ROOT_LOGGER.cannotObtainExceptionRepositoryID(clz.getName(), e); } } } /** * Gets the exception <code>Class</code>. */ Class getExceptionClass() { return clz; } /** * Writes an exception to a CDR output stream. */ public void write(OutputStream out, Object excep) { if (writeMethod != null) { try { writeMethod.invoke(null, new Object[]{out, excep}); } catch (IllegalAccessException e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (java.lang.reflect.InvocationTargetException e) { throw IIOPLogger.ROOT_LOGGER.errorMarshaling(IDLEntity.class, e.getTargetException()); } } else { out.write_string(reposId); out.write_value((Exception) excep, clz); } } /** * Sorts an <code>ExceptionWriter</code> array so that no derived * exception strategy appears after a base exception strategy. */ static void arraysort(ExceptionWriter[] a) { int len = a.length; for (int i = 0; i < len - 1; i++) { for (int j = i + 1; j < len; j++) { if (a[i].clz.isAssignableFrom(a[j].clz)) { ExceptionWriter tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } } } } // end of inner class ExceptionWriter }
10,022
34.542553
106
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ContainedImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import java.nio.charset.StandardCharsets; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.Container; import org.omg.CORBA.ContainerHelper; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.Repository; import org.omg.CORBA.RepositoryHelper; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Abstract base class for all contained IR entities. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ abstract class ContainedImpl extends IRObjectImpl implements LocalContained { ContainedImpl(String id, String name, String version, LocalContainer defined_in, DefinitionKind def_kind, RepositoryImpl repository) { super(def_kind, repository); this.id = id; this.name = name; this.version = version; this.defined_in = defined_in; if (defined_in instanceof LocalContained) this.absolute_name = ((LocalContained) defined_in).absolute_name() + "::" + name; else // must be Repository this.absolute_name = "::" + name; } public String id() { return id; } public void id(String id) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public String name() { return name; } public void name(String name) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public String version() { return version; } public void version(String version) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public Container defined_in() { return ContainerHelper.narrow(defined_in.getReference()); } public String absolute_name() { return absolute_name; } public Repository containing_repository() { return RepositoryHelper.narrow(repository.getReference()); } public abstract Description describe(); public void move(Container new_container, String new_name, String new_version) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } /** * The global repository ID of this object. */ protected String id; /** * The name of this object within its container. */ protected String name; /** * The version of this object. Defaults to 1.0. */ protected String version = "1.0"; /** * The container this is defined in. * This may not be the same as the container this is contained in. */ protected LocalContainer defined_in; /** * The absolute name of this object. */ protected String absolute_name; /** * Return the POA object ID of this IR object. * Contained objects use the UTF-8 encoding of their id, prefixed by * "repository_name:". */ protected byte[] getObjectId() { return (getRepository().getObjectIdPrefix() + id).getBytes(StandardCharsets.UTF_8); } }
4,078
28.773723
91
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/LocalContainer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.ContainerOperations; import org.omg.CORBA.DefinitionKind; /** * Interface of local containers. * Those who delegate the container implementation to the * ContainerImplDelegate should implement this interface. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ interface LocalContainer extends ContainerOperations, LocalIRObject { /** * Same as org.omg.CORBA.Contained.lookup(), * but returns local objects instead. */ LocalContained _lookup(String search_name); /** * Same as org.omg.CORBA.Contained.contents(), * but returns local objects instead. */ LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited); /** * Same as org.omg.CORBA.Contained.lookup_name(), * but returns local objects instead. */ LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited); /** * Add an entry to the delegating container. */ void add(String name, LocalContained contained) throws IRConstructionException; }
2,397
35.892308
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/OperationDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.Any; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.ExceptionDescription; import org.omg.CORBA.ExceptionDescriptionHelper; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.OperationDef; import org.omg.CORBA.OperationDefOperations; import org.omg.CORBA.OperationDefPOATie; import org.omg.CORBA.OperationDescription; import org.omg.CORBA.OperationDescriptionHelper; import org.omg.CORBA.OperationMode; import org.omg.CORBA.ParameterDescription; import org.omg.CORBA.TypeCode; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * OperationDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class OperationDefImpl extends ContainedImpl implements OperationDefOperations { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- OperationDefImpl(String id, String name, String version, LocalContainer defined_in, TypeCode typeCode, ParameterDescription[] params, ExceptionDef[] exceptions, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Operation, repository); this.typeCode = typeCode; this.params = params; this.exceptions = exceptions; } // Public -------------------------------------------------------- // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.OperationDefHelper.narrow( servantToReference(new OperationDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my return type definition: It should have been created now. type_def = IDLTypeImpl.getIDLType(typeCode, repository); // resolve parameter type definitions for (int i = 0; i < params.length; ++i) { LocalIDLType lit = IDLTypeImpl.getIDLType(params[i].type, repository); if (lit == null) throw new RuntimeException(); params[i].type_def = IDLTypeHelper.narrow(lit.getReference()); if (params[i].type_def == null) throw new RuntimeException(); } getReference(); } // OperationDefOperations implementation ---------------------------- public TypeCode result() { return typeCode; } public IDLType result_def() { return IDLTypeHelper.narrow(type_def.getReference()); } public void result_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ParameterDescription[] params() { return params; } public void params(ParameterDescription[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public OperationMode mode() { // RMI/IIOP never map to oneway operations. return OperationMode.OP_NORMAL; } public void mode(OperationMode arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public String[] contexts() { // TODO return new String[0]; } public void contexts(String[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ExceptionDef[] exceptions() { return exceptions; } public void exceptions(ExceptionDef[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); ExceptionDescription[] exds; exds = new ExceptionDescription[exceptions.length]; for (int i = 0; i < exceptions.length; ++i) { Description d = exceptions[i].describe(); exds[i] = ExceptionDescriptionHelper.extract(d.value); } OperationDescription od; od = new OperationDescription(name, id, defined_in_id, version, typeCode, mode(), contexts(), params(), exds); Any any = getORB().create_any(); OperationDescriptionHelper.insert(any, od); return new Description(DefinitionKind.dk_Operation, any); } // Package protected --------------------------------------------- // Private ------------------------------------------------------- /** * My CORBA reference. */ private OperationDef ref = null; /** * My result TypeCode. */ private TypeCode typeCode; /** * My result type definition. */ private LocalIDLType type_def; /** * My parameter description. */ private ParameterDescription[] params; /** * My exceptions. */ private ExceptionDef[] exceptions; }
6,563
29.816901
82
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ValueBoxDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TypeCodePackage.BadKind; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.ValueBoxDefOperations; import org.omg.CORBA.ValueBoxDefPOATie; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * ValueBoxDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ValueBoxDefImpl extends TypedefDefImpl implements ValueBoxDefOperations { ValueBoxDefImpl(String id, String name, String version, LocalContainer defined_in, TypeCode typeCode, RepositoryImpl repository) { super(id, name, version, defined_in, typeCode, DefinitionKind.dk_ValueBox, repository); } public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.ValueBoxDefHelper.narrow( servantToReference(new ValueBoxDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my original type definition: It should have been created now. try { original_type_def = IDLTypeImpl.getIDLType(type().content_type(), repository); } catch (BadKind ex) { throw IIOPLogger.ROOT_LOGGER.badKindForTypeCode(type().kind().value()); } getReference(); } public IDLType original_type_def() { return IDLTypeHelper.narrow(original_type_def.getReference()); } public void original_type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } /** * My CORBA reference. */ private ValueBoxDef ref = null; /** * My original IDL type. */ private LocalIDLType original_type_def; }
3,030
33.05618
83
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/PrimitiveDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TCKind; import org.omg.CORBA.IRObject; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.PrimitiveKind; import org.omg.CORBA.PrimitiveDef; import org.omg.CORBA.PrimitiveDefOperations; import org.omg.CORBA.PrimitiveDefPOATie; import java.util.Map; import java.util.HashMap; /** * PrimitiveDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class PrimitiveDefImpl extends IDLTypeImpl implements PrimitiveDefOperations, LocalIDLType { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- PrimitiveDefImpl(TypeCode typeCode, RepositoryImpl repository) { super(typeCode, DefinitionKind.dk_Primitive, repository); } // Public -------------------------------------------------------- // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.PrimitiveDefHelper.narrow( servantToReference(new PrimitiveDefPOATie(this))); } return ref; } // PrimitiveDefOperations implementation ---------------------------- public PrimitiveKind kind() { return (PrimitiveKind) primitiveTCKindMap.get(type().kind()); } // Package protected --------------------------------------------- static boolean isPrimitiveTCKind(TCKind tcKind) { return primitiveTCKindMap.containsKey(tcKind); } // Private ------------------------------------------------------- /** * My CORBA reference. */ private PrimitiveDef ref = null; /** * Maps TCKind to PrimitiveKind. */ private static Map primitiveTCKindMap; static { // Create and initialize the map primitiveTCKindMap = new HashMap(); primitiveTCKindMap.put(TCKind.tk_null, PrimitiveKind.pk_null); primitiveTCKindMap.put(TCKind.tk_void, PrimitiveKind.pk_void); primitiveTCKindMap.put(TCKind.tk_short, PrimitiveKind.pk_short); primitiveTCKindMap.put(TCKind.tk_long, PrimitiveKind.pk_long); primitiveTCKindMap.put(TCKind.tk_ushort, PrimitiveKind.pk_ushort); primitiveTCKindMap.put(TCKind.tk_ulong, PrimitiveKind.pk_ulong); primitiveTCKindMap.put(TCKind.tk_float, PrimitiveKind.pk_float); primitiveTCKindMap.put(TCKind.tk_double, PrimitiveKind.pk_double); primitiveTCKindMap.put(TCKind.tk_boolean, PrimitiveKind.pk_boolean); primitiveTCKindMap.put(TCKind.tk_char, PrimitiveKind.pk_char); primitiveTCKindMap.put(TCKind.tk_octet, PrimitiveKind.pk_octet); primitiveTCKindMap.put(TCKind.tk_any, PrimitiveKind.pk_any); primitiveTCKindMap.put(TCKind.tk_TypeCode, PrimitiveKind.pk_TypeCode); primitiveTCKindMap.put(TCKind.tk_Principal, PrimitiveKind.pk_Principal); primitiveTCKindMap.put(TCKind.tk_objref, PrimitiveKind.pk_objref); primitiveTCKindMap.put(TCKind.tk_string, PrimitiveKind.pk_string); primitiveTCKindMap.put(TCKind.tk_longlong, PrimitiveKind.pk_longlong); primitiveTCKindMap.put(TCKind.tk_ulonglong, PrimitiveKind.pk_ulonglong); primitiveTCKindMap.put(TCKind.tk_longdouble, PrimitiveKind.pk_longdouble); primitiveTCKindMap.put(TCKind.tk_wchar, PrimitiveKind.pk_wchar); primitiveTCKindMap.put(TCKind.tk_wstring, PrimitiveKind.pk_wstring); } }
4,780
37.556452
82
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ContainerImplDelegate.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.omg.CORBA.AliasDef; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedHelper; import org.omg.CORBA.Container; import org.omg.CORBA.ContainerOperations; import org.omg.CORBA.ContainerPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.IDLType; import org.omg.CORBA.Initializer; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.StructDef; import org.omg.CORBA.StructMember; import org.omg.CORBA.UnionDef; import org.omg.CORBA.UnionMember; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.ValueDef; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Delegate for Container functionality. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ContainerImplDelegate implements ContainerOperations { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- /** * Create a new delegate. */ ContainerImplDelegate(LocalContainer delegateFor) { this.delegateFor = delegateFor; } // Public -------------------------------------------------------- // LocalContainer delegation implementation ---------------------- public LocalContained _lookup(String search_name) { if (search_name.startsWith("::")) return delegateFor.getRepository()._lookup(search_name.substring(2)); int idx = search_name.indexOf("::"); if (idx > 0) { String first = search_name.substring(0, idx); Object o = contMap.get(first); if (o == null || !(o instanceof LocalContainer)) return null; else { LocalContainer next = (LocalContainer) o; String rest = search_name.substring(idx + 2); return next._lookup(rest); } } else return (LocalContained) contMap.get(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { int target = limit_type.value(); Collection found; if (target == DefinitionKind._dk_all) found = cont; else { found = new ArrayList(); for (int i = 0; i < cont.size(); ++i) { LocalContained val = (LocalContained) cont.get(i); if (target == val.def_kind().value() && (!exclude_inherited || val.defined_in() == delegateFor)) { found.add(val); } } } LocalContained[] res = new LocalContained[found.size()]; res = (LocalContained[]) found.toArray(res); return res; } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { if (levels_to_search == 0) return null; if (levels_to_search == -1) ++levels_to_search; // One more level (recursively) == all levels Collection found = new ArrayList(); LocalContained[] here = _contents(limit_type, exclude_inherited); for (int i = 0; i < here.length; ++i) if (here[i].name().equals(search_name)) found.add(here[i]); if (levels_to_search >= 0) { // More levels to search, or unlimited depth search for (int i = 0; i < here.length; ++i) { if (here[i] instanceof Container) { // search here LocalContainer container = (LocalContainer) here[i]; LocalContained[] c; c = container._lookup_name(search_name, levels_to_search - 1, limit_type, exclude_inherited); if (c != null) for (int j = 0; j < c.length; ++j) found.add(c[j]); } } } LocalContained[] res = new LocalContained[found.size()]; res = (LocalContained[]) found.toArray(res); return res; } public void shutdown() { for (int i = 0; i < cont.size(); ++i) ((LocalContained) cont.get(i)).shutdown(); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { LocalContained c = _lookup(search_name); if (c == null) return null; else return ContainedHelper.narrow(c.getReference()); } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { LocalContained[] c = _contents(limit_type, exclude_inherited); Contained[] res = new Contained[c.length]; for (int i = 0; i < c.length; ++i) res[i] = ContainedHelper.narrow(c[i].getReference()); return res; } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { LocalContained[] c = _lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); Contained[] res = new Contained[c.length]; for (int i = 0; i < c.length; ++i) res[i] = ContainedHelper.narrow(c[i].getReference()); return res; } public Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { Contained[] c = contents(limit_type, exclude_inherited); int returnSize; if (max_returned_objs != -1 && c.length > max_returned_objs) returnSize = max_returned_objs; else returnSize = c.length; Description[] ret = new Description[returnSize]; for (int i = 0; i < returnSize; ++i) { org.omg.CORBA.ContainedPackage.Description d = c[i].describe(); ret[i] = new Description(c[i], d.kind, d.value); } return ret; } public ModuleDef create_module(String id, String name, String version) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ConstantDef create_constant(String id, String name, String version, IDLType type, org.omg.CORBA.Any value) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public EnumDef create_enum(String id, String name, String version, String[] members) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public NativeDef create_native(String id, String name, String version) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // Dummy IRObjectOperations implementation ----------------------- public DefinitionKind def_kind() { throw new UnsupportedOperationException(); } public void destroy() { throw new UnsupportedOperationException(); } // Package protected --------------------------------------------- void add(String name, LocalContained contained) throws IRConstructionException { if (contained.getRepository() != delegateFor.getRepository()) throw IIOPLogger.ROOT_LOGGER.wrongInterfaceRepository(); if (contMap.get(name) != null) throw IIOPLogger.ROOT_LOGGER.duplicateRepositoryName(); cont.add(contained); contMap.put(name, contained); } /** * Finalize build process, and export. */ void allDone() throws IRConstructionException { for (int i = 0; i < cont.size(); ++i) { LocalContained item = (LocalContained) cont.get(i); item.allDone(); } } // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * The contents of the Container. */ private ArrayList cont = new ArrayList(); /** * Maps names to the contents of the Container. */ private Map contMap = new HashMap(); /** * The Container I am a delegate for. */ private LocalContainer delegateFor; // Inner classes ------------------------------------------------- }
12,023
34.157895
85
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ValueMemberDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.Any; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.PRIVATE_MEMBER; import org.omg.CORBA.PUBLIC_MEMBER; import org.omg.CORBA.TypeCode; import org.omg.CORBA.ValueMember; import org.omg.CORBA.ValueMemberDef; import org.omg.CORBA.ValueMemberDefOperations; import org.omg.CORBA.ValueMemberDefPOATie; import org.omg.CORBA.ValueMemberHelper; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * ValueMemberDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ValueMemberDefImpl extends ContainedImpl implements ValueMemberDefOperations { ValueMemberDefImpl(String id, String name, String version, TypeCode typeCode, boolean publicMember, LocalContainer defined_in, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_ValueMember, repository); this.typeCode = typeCode; this.publicMember = publicMember; } public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.ValueMemberDefHelper.narrow( servantToReference(new ValueMemberDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my type definition: It should have been created now. type_def = IDLTypeImpl.getIDLType(typeCode, repository); getReference(); } public TypeCode type() { return typeCode; } public IDLType type_def() { return IDLTypeHelper.narrow(type_def.getReference()); } public void type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public short access() { return (publicMember) ? PUBLIC_MEMBER.value : PRIVATE_MEMBER.value; } public void access(short arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); ValueMember d = new ValueMember(name, id, defined_in_id, version, typeCode, type_def(), access()); Any any = getORB().create_any(); ValueMemberHelper.insert(any, d); return new Description(DefinitionKind.dk_ValueMember, any); } /** * My CORBA reference. */ private ValueMemberDef ref = null; /** * My TypeCode. */ private TypeCode typeCode; /** * My type definition. */ private LocalIDLType type_def; /** * Flags that this member is public. */ private boolean publicMember; }
4,094
30.022727
84
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/LocalContainedIDLType.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; /** * Interface of local contained IDL types. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ interface LocalContainedIDLType extends LocalIDLType, LocalContained { }
1,293
37.058824
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/LocalContained.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.ContainedOperations; /** * Interface of local contained IR objects. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ interface LocalContained extends ContainedOperations, LocalIRObject { /** * Get a reference to the local IR implementation that * this Contained object exists in. */ RepositoryImpl getRepository(); }
1,494
35.463415
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/InterfaceDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.AliasDef; import org.omg.CORBA.Any; import org.omg.CORBA.AttributeDef; import org.omg.CORBA.AttributeDescription; import org.omg.CORBA.AttributeMode; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.IDLType; import org.omg.CORBA.IRObject; import org.omg.CORBA.Initializer; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.InterfaceDefHelper; import org.omg.CORBA.InterfaceDefOperations; import org.omg.CORBA.InterfaceDefPOATie; import org.omg.CORBA.InterfaceDefPackage.FullInterfaceDescription; import org.omg.CORBA.InterfaceDescription; import org.omg.CORBA.InterfaceDescriptionHelper; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.OperationDef; import org.omg.CORBA.OperationDescription; import org.omg.CORBA.OperationMode; import org.omg.CORBA.ParameterDescription; import org.omg.CORBA.StructDef; import org.omg.CORBA.StructMember; import org.omg.CORBA.TypeCode; import org.omg.CORBA.UnionDef; import org.omg.CORBA.UnionMember; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.ValueDef; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Interface IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class InterfaceDefImpl extends ContainedImpl implements InterfaceDefOperations, LocalContainer { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- InterfaceDefImpl(String id, String name, String version, LocalContainer defined_in, String[] base_interfaces, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Interface, repository); this.base_interfaces = base_interfaces; this.delegate = new ContainerImplDelegate(this); } // Public -------------------------------------------------------- // LocalContainer implementation --------------------------------- public LocalContained _lookup(String search_name) { return delegate._lookup(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate._contents(limit_type, exclude_inherited); } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate._lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public void add(String name, LocalContained contained) throws IRConstructionException { delegate.add(name, contained); } // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = InterfaceDefHelper.narrow( servantToReference(new InterfaceDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { getReference(); delegate.allDone(); } public void shutdown() { delegate.shutdown(); super.shutdown(); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { Contained res = delegate.lookup(search_name); return res; } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate.contents(limit_type, exclude_inherited); } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate.lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public org.omg.CORBA.ContainerPackage.Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return delegate.describe_contents(limit_type, exclude_inherited, max_returned_objs); } public ModuleDef create_module(String id, String name, String version) { return delegate.create_module(id, name, version); } public ConstantDef create_constant(String id, String name, String version, IDLType type, Any value) { return delegate.create_constant(id, name, version, type, value); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { return delegate.create_struct(id, name, version, members); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { return delegate.create_union(id, name, version, discriminator_type, members); } public EnumDef create_enum(String id, String name, String version, String[] members) { return delegate.create_enum(id, name, version, members); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { return delegate.create_alias(id, name, version, original_type); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { return delegate.create_interface(id, name, version, base_interfaces, is_abstract); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { return delegate.create_value(id, name, version, is_custom, is_abstract, base_value, is_truncatable, abstract_base_values, supported_interfaces, initializers); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { return delegate.create_value_box(id, name, version, original_type_def); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { return delegate.create_exception(id, name, version, members); } public NativeDef create_native(String id, String name, String version) { return delegate.create_native(id, name, version); } // InterfaceDefOperations implementation ------------------------- public InterfaceDef[] base_interfaces() { if (base_interfaces_ref == null) { base_interfaces_ref = new InterfaceDef[base_interfaces.length]; for (int i = 0; i < base_interfaces_ref.length; ++i) { Contained c = repository.lookup_id(base_interfaces[i]); base_interfaces_ref[i] = InterfaceDefHelper.narrow(c); } } return base_interfaces_ref; } public void base_interfaces(InterfaceDef[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_abstract() { return false; } public void is_abstract(boolean arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_a(String interface_id) { // TODO return false; } public FullInterfaceDescription describe_interface() { if (fullInterfaceDescription != null) return fullInterfaceDescription; // Has to create the FullInterfaceDescription // TODO OperationDescription[] operations = new OperationDescription[0]; AttributeDescription[] attributes = new AttributeDescription[0]; String defined_in_id = "IDL:Global:1.0"; if (defined_in instanceof org.omg.CORBA.ContainedOperations) defined_in_id = ((org.omg.CORBA.ContainedOperations) defined_in).id(); fullInterfaceDescription = new FullInterfaceDescription(name, id, defined_in_id, version, operations, attributes, base_interfaces, type(), is_abstract); return fullInterfaceDescription; } public AttributeDef create_attribute(String id, String name, String version, IDLType type, AttributeMode mode) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public OperationDef create_operation(String id, String name, String version, IDLType result, OperationMode mode, ParameterDescription[] params, ExceptionDef[] exceptions, String[] contexts) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // IDLTypeOperations implementation ------------------------------ public TypeCode type() { if (typeCode == null) typeCode = getORB().create_interface_tc(id, name); return typeCode; } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof org.omg.CORBA.ContainedOperations) defined_in_id = ((org.omg.CORBA.ContainedOperations) defined_in).id(); InterfaceDescription md = new InterfaceDescription(name, id, defined_in_id, version, base_interfaces, false); Any any = getORB().create_any(); InterfaceDescriptionHelper.insert(any, md); return new Description(DefinitionKind.dk_Interface, any); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- /** * My CORBA reference. */ protected InterfaceDef ref = null; /** * My cached TypeCode. */ protected TypeCode typeCode; // Private ------------------------------------------------------- /** * My delegate for Container functionality. */ private ContainerImplDelegate delegate; /** * Flag that I am abstract. */ private boolean is_abstract; /** * IDs of my superinterfaces. */ private String[] base_interfaces; /** * CORBA references of my superinterfaces. */ private InterfaceDef[] base_interfaces_ref; /** * My cached FullInterfaceDescription. */ private FullInterfaceDescription fullInterfaceDescription; // Inner classes ------------------------------------------------- }
13,117
34.358491
82
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ExceptionDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.AliasDef; import org.omg.CORBA.Any; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.ExceptionDefOperations; import org.omg.CORBA.ExceptionDefPOATie; import org.omg.CORBA.ExceptionDescription; import org.omg.CORBA.ExceptionDescriptionHelper; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.Initializer; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.StructDef; import org.omg.CORBA.StructMember; import org.omg.CORBA.TypeCode; import org.omg.CORBA.UnionDef; import org.omg.CORBA.UnionMember; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.ValueDef; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Abstract base class for all contained IR entities. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ExceptionDefImpl extends ContainedImpl implements ExceptionDefOperations, LocalContainer { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- ExceptionDefImpl(String id, String name, String version, TypeCode typeCode, ValueDefImpl vDef, LocalContainer defined_in, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Exception, repository); this.delegate = new ContainerImplDelegate(this); this.typeCode = typeCode; this.vDef = vDef; } // Public -------------------------------------------------------- // LocalContainer implementation --------------------------------- public LocalContained _lookup(String search_name) { return delegate._lookup(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate._contents(limit_type, exclude_inherited); } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate._lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public void add(String name, LocalContained contained) throws IRConstructionException { throw new UnsupportedOperationException(); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { return delegate.lookup(search_name); } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate.contents(limit_type, exclude_inherited); } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate.lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public org.omg.CORBA.ContainerPackage.Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return delegate.describe_contents(limit_type, exclude_inherited, max_returned_objs); } public ModuleDef create_module(String id, String name, String version) { return delegate.create_module(id, name, version); } public ConstantDef create_constant(String id, String name, String version, IDLType type, Any value) { return delegate.create_constant(id, name, version, type, value); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { return delegate.create_struct(id, name, version, members); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { return delegate.create_union(id, name, version, discriminator_type, members); } public EnumDef create_enum(String id, String name, String version, String[] members) { return delegate.create_enum(id, name, version, members); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { return delegate.create_alias(id, name, version, original_type); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { return delegate.create_interface(id, name, version, base_interfaces, is_abstract); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { return delegate.create_value(id, name, version, is_custom, is_abstract, base_value, is_truncatable, abstract_base_values, supported_interfaces, initializers); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { return delegate.create_value_box(id, name, version, original_type_def); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { return delegate.create_exception(id, name, version, members); } public NativeDef create_native(String id, String name, String version) { return delegate.create_native(id, name, version); } // LocalIRObject implementation ---------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.ExceptionDefHelper.narrow( servantToReference(new ExceptionDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { getReference(); delegate.allDone(); } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); ExceptionDescription ed = new ExceptionDescription(name, id, defined_in_id, version, type()); Any any = getORB().create_any(); ExceptionDescriptionHelper.insert(any, ed); return new Description(DefinitionKind.dk_Exception, any); } // ExceptionDefOperations implementation ------------------------- public TypeCode type() { return typeCode; } public StructMember[] members() { if (members == null) { TypeCode type = vDef.type(); LocalIDLType localTypeDef = IDLTypeImpl.getIDLType(type, repository); IDLType type_def = IDLTypeHelper.narrow(localTypeDef.getReference()); members = new StructMember[1]; members[0] = new StructMember("value", type, type_def); } return members; } public void members(StructMember[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * My delegate for Container functionality. */ private ContainerImplDelegate delegate; /** * My CORBA reference. */ private ExceptionDef ref = null; /** * My TypeCode. */ private TypeCode typeCode; /** * The value I contain as my only member. */ ValueDefImpl vDef; /** * My members. */ private StructMember[] members; // Inner classes ------------------------------------------------- }
10,331
34.750865
81
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/TypedefDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.TypeCode; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.TypedefDefOperations; import org.omg.CORBA.Any; import org.omg.CORBA.TypeDescription; import org.omg.CORBA.TypeDescriptionHelper; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; /** * TypedefDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ abstract class TypedefDefImpl extends ContainedImpl implements TypedefDefOperations, LocalContainedIDLType { TypedefDefImpl(String id, String name, String version, LocalContainer defined_in, TypeCode typeCode, DefinitionKind def_kind, RepositoryImpl repository) { super(id, name, version, defined_in, def_kind, repository); this.typeCode = typeCode; } // Public -------------------------------------------------------- // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); TypeDescription td = new TypeDescription(name, id, defined_in_id, version, typeCode); Any any = getORB().create_any(); TypeDescriptionHelper.insert(any, td); return new Description(DefinitionKind.dk_Typedef, any); } // IDLTypeOperations implementation ------------------------------- public TypeCode type() { return typeCode; } // Package protected --------------------------------------------- // Private ------------------------------------------------------- /** * My TypeCode. */ private TypeCode typeCode; }
2,924
32.62069
73
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/IDLTypeImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TypeCodePackage.BadKind; import org.omg.CORBA.TCKind; import org.omg.CORBA.DefinitionKind; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * IDLType IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ abstract class IDLTypeImpl extends IRObjectImpl implements LocalIDLType { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- IDLTypeImpl(TypeCode typeCode, DefinitionKind def_kind, RepositoryImpl repository) { super(def_kind, repository); this.typeCode = typeCode; } // Public -------------------------------------------------------- // IDLTypeOperations implementation --------------------------------- public TypeCode type() { return typeCode; } // Package protected --------------------------------------------- /** * Return the LocalIDLType for the given TypeCode. */ static LocalIDLType getIDLType(TypeCode typeCode, RepositoryImpl repository) { TCKind tcKind = typeCode.kind(); if (PrimitiveDefImpl.isPrimitiveTCKind(tcKind)) return new PrimitiveDefImpl(typeCode, repository); if (tcKind == TCKind.tk_sequence) return repository.getSequenceImpl(typeCode); if (tcKind == TCKind.tk_value || tcKind == TCKind.tk_value_box || tcKind == TCKind.tk_alias || tcKind == TCKind.tk_struct || tcKind == TCKind.tk_union || tcKind == TCKind.tk_enum || tcKind == TCKind.tk_objref) { try { return (LocalIDLType) repository._lookup_id(typeCode.id()); } catch (BadKind ex) { throw IIOPLogger.ROOT_LOGGER.badKindForTypeCode(tcKind.value()); } } throw IIOPLogger.ROOT_LOGGER.badKindForTypeCode(tcKind.value()); } // Protected ----------------------------------------------------- /** * Return the POA object ID of this IR object. * We delegate to the IR to get a serial number ID. */ protected byte[] getObjectId() { return repository.getNextObjectId(); } // Private ------------------------------------------------------- /** * My TypeCode. */ private TypeCode typeCode; }
3,661
32.59633
82
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ModuleDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.ModuleDefOperations; import org.omg.CORBA.ModuleDefPOATie; import org.omg.CORBA.Any; import org.omg.CORBA.IRObject; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.IDLType; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.StructMember; import org.omg.CORBA.UnionMember; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ValueDef; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.Initializer; import org.omg.CORBA.StructDef; import org.omg.CORBA.UnionDef; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.AliasDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.ModuleDescription; import org.omg.CORBA.ModuleDescriptionHelper; /** * Abstract base class for all contained IR entities. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ModuleDefImpl extends ContainedImpl implements ModuleDefOperations, LocalContainer { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- ModuleDefImpl(String id, String name, String version, LocalContainer defined_in, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Module, repository); this.delegate = new ContainerImplDelegate(this); } // Public -------------------------------------------------------- // LocalContainer implementation --------------------------------- public LocalContained _lookup(String search_name) { return delegate._lookup(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate._contents(limit_type, exclude_inherited); } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate._lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public void add(String name, LocalContained contained) throws IRConstructionException { delegate.add(name, contained); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { return delegate.lookup(search_name); } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate.contents(limit_type, exclude_inherited); } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate.lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public org.omg.CORBA.ContainerPackage.Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return delegate.describe_contents(limit_type, exclude_inherited, max_returned_objs); } public ModuleDef create_module(String id, String name, String version) { return delegate.create_module(id, name, version); } public ConstantDef create_constant(String id, String name, String version, IDLType type, Any value) { return delegate.create_constant(id, name, version, type, value); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { return delegate.create_struct(id, name, version, members); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { return delegate.create_union(id, name, version, discriminator_type, members); } public EnumDef create_enum(String id, String name, String version, String[] members) { return delegate.create_enum(id, name, version, members); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { return delegate.create_alias(id, name, version, original_type); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { return delegate.create_interface(id, name, version, base_interfaces, is_abstract); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { return delegate.create_value(id, name, version, is_custom, is_abstract, base_value, is_truncatable, abstract_base_values, supported_interfaces, initializers); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { return delegate.create_value_box(id, name, version, original_type_def); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { return delegate.create_exception(id, name, version, members); } public NativeDef create_native(String id, String name, String version) { return delegate.create_native(id, name, version); } // LocalIRObject implementation ---------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.ModuleDefHelper.narrow( servantToReference(new ModuleDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { getReference(); delegate.allDone(); } public void shutdown() { delegate.shutdown(); super.shutdown(); } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); ModuleDescription md = new ModuleDescription(name, id, defined_in_id, version); Any any = getORB().create_any(); ModuleDescriptionHelper.insert(any, md); return new Description(DefinitionKind.dk_Module, any); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * My delegate for Container functionality. */ private ContainerImplDelegate delegate; /** * My CORBA reference. */ private ModuleDef ref = null; // Inner classes ------------------------------------------------- }
9,265
35.916335
80
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ContainerImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.ContainerOperations; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainerPackage.Description; import org.omg.CORBA.IDLType; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.StructMember; import org.omg.CORBA.UnionMember; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ValueDef; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.Initializer; import org.omg.CORBA.StructDef; import org.omg.CORBA.UnionDef; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.AliasDef; import org.omg.CORBA.Any; import org.omg.CORBA.ExceptionDef; /** * Abstract base class for container IR entities. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ abstract class ContainerImpl extends IRObjectImpl implements ContainerOperations, LocalContainer { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- ContainerImpl(DefinitionKind def_kind, RepositoryImpl repository) { super(def_kind, repository); this.delegate = new ContainerImplDelegate(this); } // Public -------------------------------------------------------- // LocalContainer implementation --------------------------------- public LocalContained _lookup(String search_name) { return delegate._lookup(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate._contents(limit_type, exclude_inherited); } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate._lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public void add(String name, LocalContained contained) throws IRConstructionException { delegate.add(name, contained); } public void allDone() throws IRConstructionException { getReference(); delegate.allDone(); } public void shutdown() { delegate.shutdown(); super.shutdown(); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { return delegate.lookup(search_name); } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate.contents(limit_type, exclude_inherited); } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate.lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return delegate.describe_contents(limit_type, exclude_inherited, max_returned_objs); } public ModuleDef create_module(String id, String name, String version) { return delegate.create_module(id, name, version); } public ConstantDef create_constant(String id, String name, String version, IDLType type, Any value) { return delegate.create_constant(id, name, version, type, value); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { return delegate.create_struct(id, name, version, members); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { return delegate.create_union(id, name, version, discriminator_type, members); } public EnumDef create_enum(String id, String name, String version, String[] members) { return delegate.create_enum(id, name, version, members); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { return delegate.create_alias(id, name, version, original_type); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { return delegate.create_interface(id, name, version, base_interfaces, is_abstract); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { return delegate.create_value(id, name, version, is_custom, is_abstract, base_value, is_truncatable, abstract_base_values, supported_interfaces, initializers); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { return delegate.create_value_box(id, name, version, original_type_def); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { return delegate.create_exception(id, name, version, members); } public NativeDef create_native(String id, String name, String version) { return delegate.create_native(id, name, version); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * My delegate for Container functionality. */ ContainerImplDelegate delegate; // Inner classes ------------------------------------------------- }
8,036
37.090047
80
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/LocalIDLType.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.IDLTypeOperations; /** * Interface of local IDL types. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ interface LocalIDLType extends IDLTypeOperations, LocalIRObject { }
1,319
36.714286
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/AttributeDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.Any; import org.omg.CORBA.AttributeDef; import org.omg.CORBA.AttributeDefOperations; import org.omg.CORBA.AttributeDefPOATie; import org.omg.CORBA.AttributeDescription; import org.omg.CORBA.AttributeDescriptionHelper; import org.omg.CORBA.AttributeMode; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.TypeCode; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Attribute IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class AttributeDefImpl extends ContainedImpl implements AttributeDefOperations { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- AttributeDefImpl(String id, String name, String version, AttributeMode mode, TypeCode typeCode, LocalContainer defined_in, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Attribute, repository); this.mode = mode; this.typeCode = typeCode; } // Public -------------------------------------------------------- // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.AttributeDefHelper.narrow( servantToReference(new AttributeDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my type definition: It should have been created now. type_def = IDLTypeImpl.getIDLType(typeCode, repository); getReference(); } // AttributeDefOperations implementation ---------------------------- public TypeCode type() { return typeCode; } public IDLType type_def() { return IDLTypeHelper.narrow(type_def.getReference()); } public void type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public AttributeMode mode() { return mode; } public void mode(AttributeMode arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); AttributeDescription d = new AttributeDescription(name, id, defined_in_id, version, typeCode, mode); Any any = getORB().create_any(); AttributeDescriptionHelper.insert(any, d); return new Description(DefinitionKind.dk_Attribute, any); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * My CORBA reference. */ private AttributeDef ref = null; /** * My mode. */ private AttributeMode mode; /** * My TypeCode. */ private TypeCode typeCode; /** * My type definition. */ private LocalIDLType type_def; // Inner classes ------------------------------------------------- }
4,933
29.085366
76
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/SequenceDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.SequenceDef; import org.omg.CORBA.SequenceDefOperations; import org.omg.CORBA.SequenceDefPOATie; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TypeCodePackage.BadKind; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * SequenceDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class SequenceDefImpl extends IDLTypeImpl implements SequenceDefOperations { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- SequenceDefImpl(TypeCode typeCode, RepositoryImpl repository) { super(typeCode, DefinitionKind.dk_Sequence, repository); } // Public -------------------------------------------------------- // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.SequenceDefHelper.narrow( servantToReference(new SequenceDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my element type definition: It should have been created now. try { element_type_def = IDLTypeImpl.getIDLType(type().content_type(), repository); } catch (BadKind ex) { throw IIOPLogger.ROOT_LOGGER.badKindForTypeCode(type().kind().value()); } getReference(); } // SequenceDefOperations implementation -------------------------- public int bound() { try { return type().length(); } catch (BadKind ex) { // should never happen throw new RuntimeException(); } } public void bound(int arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public TypeCode element_type() { try { return type().content_type(); } catch (BadKind ex) { // should never happen throw new RuntimeException(); } } public IDLType element_type_def() { return IDLTypeHelper.narrow(element_type_def.getReference()); } public void element_type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // Package protected --------------------------------------------- // Private ------------------------------------------------------- /** * My CORBA reference. */ private SequenceDef ref = null; /** * My element type. */ private LocalIDLType element_type_def; }
4,051
30.410853
83
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/AliasDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.AliasDef; import org.omg.CORBA.AliasDefOperations; import org.omg.CORBA.AliasDefPOATie; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TypeCodePackage.BadKind; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * AliasDef IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class AliasDefImpl extends TypedefDefImpl implements AliasDefOperations { AliasDefImpl(String id, String name, String version, LocalContainer defined_in, TypeCode typeCode, RepositoryImpl repository) { super(id, name, version, defined_in, typeCode, DefinitionKind.dk_Alias, repository); } public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.AliasDefHelper.narrow( servantToReference(new AliasDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my original type definition: It should have been created now. try { original_type_def = IDLTypeImpl.getIDLType(type().content_type(), repository); } catch (BadKind ex) { throw IIOPLogger.ROOT_LOGGER.badKindForTypeCode(type().kind().value()); } getReference(); } public IDLType original_type_def() { return IDLTypeHelper.narrow(original_type_def.getReference()); } public void original_type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } /** * My CORBA reference. */ private AliasDef ref = null; /** * My original IDL type. */ private LocalIDLType original_type_def; }
2,991
32.617978
83
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/IRConstructionException.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; /** * Interface Repository construction failure exception. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class IRConstructionException extends Exception { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public IRConstructionException(String msg) { super(msg); } // Public -------------------------------------------------------- // Z implementation ---------------------------------------------- // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- }
2,167
35.133333
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ConstantDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.Any; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.ConstantDefOperations; import org.omg.CORBA.ConstantDefPOATie; import org.omg.CORBA.ConstantDescription; import org.omg.CORBA.ConstantDescriptionHelper; import org.omg.CORBA.ContainedOperations; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IDLType; import org.omg.CORBA.IDLTypeHelper; import org.omg.CORBA.IRObject; import org.omg.CORBA.TypeCode; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Constant IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class ConstantDefImpl extends ContainedImpl implements ConstantDefOperations { ConstantDefImpl(String id, String name, String version, TypeCode typeCode, Any value, LocalContainer defined_in, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Constant, repository); this.typeCode = typeCode; this.value = value; } public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.ConstantDefHelper.narrow( servantToReference(new ConstantDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { // Get my type definition: It should have been created now. type_def = IDLTypeImpl.getIDLType(typeCode, repository); getReference(); } // ConstantDefOperations implementation ---------------------------- public TypeCode type() { return typeCode; } public IDLType type_def() { return IDLTypeHelper.narrow(type_def.getReference()); } public void type_def(IDLType arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public Any value() { return value; } public void value(Any arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof ContainedOperations) defined_in_id = ((ContainedOperations) defined_in).id(); ConstantDescription d = new ConstantDescription(name, id, defined_in_id, version, typeCode, value); Any any = getORB().create_any(); ConstantDescriptionHelper.insert(any, d); return new Description(DefinitionKind.dk_Constant, any); } /** * My CORBA reference. */ private ConstantDef ref = null; /** * My TypeCode. */ private TypeCode typeCode; /** * My type definition. */ private LocalIDLType type_def; /** * My value. */ private Any value; }
4,037
28.474453
85
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/LocalIRObject.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.IRObject; import org.omg.CORBA.IRObjectOperations; /** * Interface of local IRObject implementations. * <p/> * This defines the local (non-exported) methods. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ interface LocalIRObject extends IRObjectOperations { /** * Get an exported CORBA reference to this IRObject. */ IRObject getReference(); /** * Finalize the building process, and export. */ void allDone() throws IRConstructionException; /** * Get a reference to the local IR implementation that * this IR object exists in. */ RepositoryImpl getRepository(); /** * Unexport this object. */ void shutdown(); }
1,850
30.372881
70
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/InterfaceRepository.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.omg.CORBA.Any; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.ExceptionDefHelper; import org.omg.CORBA.ORB; import org.omg.CORBA.ParameterDescription; import org.omg.CORBA.ParameterMode; import org.omg.CORBA.Repository; import org.omg.CORBA.RepositoryHelper; import org.omg.CORBA.StructMember; import org.omg.CORBA.TCKind; import org.omg.CORBA.TypeCode; import org.omg.PortableServer.POA; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.rmi.AttributeAnalysis; import org.wildfly.iiop.openjdk.rmi.ConstantAnalysis; import org.wildfly.iiop.openjdk.rmi.ContainerAnalysis; import org.wildfly.iiop.openjdk.rmi.ExceptionAnalysis; import org.wildfly.iiop.openjdk.rmi.InterfaceAnalysis; import org.wildfly.iiop.openjdk.rmi.OperationAnalysis; import org.wildfly.iiop.openjdk.rmi.ParameterAnalysis; import org.wildfly.iiop.openjdk.rmi.RMIIIOPViolationException; import org.wildfly.iiop.openjdk.rmi.RmiIdlUtil; import org.wildfly.iiop.openjdk.rmi.Util; import org.wildfly.iiop.openjdk.rmi.ValueAnalysis; import org.wildfly.iiop.openjdk.rmi.ValueMemberAnalysis; /** * An Interface Repository. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ public class InterfaceRepository { /** * The repository implementation. */ RepositoryImpl impl; /** * The ORB that I use. */ private ORB orb = null; /** * The POA that I use. */ private POA poa = null; /** * Maps java classes to IDL TypeCodes for parameter, result, attribute * and value member types. */ private final Map<Class<?>, TypeCode> typeCodeMap; /** * Maps java classes to IDL TypeCodes for parameter, result, attribute * and value member types. */ private final Map<Class<?>, TypeCode> constantTypeCodeMap; /** * Maps java classes to <code>InterfaceDefImpl</code>s for interfaces. */ private Map interfaceMap = new HashMap(); /** * Maps java classes to <code>ValueDefImpl</code>s for values. */ private Map valueMap = new HashMap(); /** * Maps java classes to <code>ExceptionDefImpl</code>s for exceptions. */ private Map exceptionMap = new HashMap(); /** * Maps java classes to <code>ValueBoxDefImpl</code>s for arrays. */ private Map arrayMap = new HashMap(); /** * java.io.Serializable special mapping, as per section 1.3.10.1. * Do not use this variable directly, use the * <code>getJavaIoSerializable()</code> method instead, as that will * create the typedef in the IR on demand. */ private AliasDefImpl javaIoSerializable = null; /** * java.io.Externalizable special mapping, as per section 1.3.10.1. * Do not use this variable directly, use the * <code>getJavaIoExternalizable()</code> method instead, as that will * create the typedef in the IR on demand. */ private AliasDefImpl javaIoExternalizable = null; /** * java.lang.Object special mapping, as per section 1.3.10.2. * Do not use this variable directly, use the * <code>getJavaLang_Object()</code> method instead, as that will * create the typedef in the IR on demand. */ private AliasDefImpl javaLang_Object = null; /** * java.lang.String special mapping, as per section 1.3.5.10. * Do not use this variable directly, use the * <code>getJavaLangString()</code> method instead, as that will * create the value type in the IR on demand. */ private ValueDefImpl javaLangString = null; /** * java.lang.Class special mapping, as per section 1.3.5.11. * Do not use this variable directly, use the * <code>getJavaxRmiCORBAClassDesc()</code> method instead, as that will * create the value type in the IR on demand. */ private ValueDefImpl javaxRmiCORBAClassDesc = null; public InterfaceRepository(ORB orb, POA poa, String name) { this.orb = orb; this.poa = poa; impl = new RepositoryImpl(orb, poa, name); // TypeCodes for primitive types final HashMap<Class<?>, TypeCode> primitiveTypeCodeMap = new HashMap<Class<?>, TypeCode>(); primitiveTypeCodeMap.put(Void.TYPE, orb.get_primitive_tc(TCKind.tk_void)); primitiveTypeCodeMap.put(Boolean.TYPE, orb.get_primitive_tc(TCKind.tk_boolean)); primitiveTypeCodeMap.put(Character.TYPE, orb.get_primitive_tc(TCKind.tk_wchar)); primitiveTypeCodeMap.put(Byte.TYPE, orb.get_primitive_tc(TCKind.tk_octet)); primitiveTypeCodeMap.put(Short.TYPE, orb.get_primitive_tc(TCKind.tk_short)); primitiveTypeCodeMap.put(Integer.TYPE, orb.get_primitive_tc(TCKind.tk_long)); primitiveTypeCodeMap.put(Long.TYPE, orb.get_primitive_tc(TCKind.tk_longlong)); primitiveTypeCodeMap.put(Float.TYPE, orb.get_primitive_tc(TCKind.tk_float)); primitiveTypeCodeMap.put(Double.TYPE, orb.get_primitive_tc(TCKind.tk_double)); this.typeCodeMap = primitiveTypeCodeMap; final HashMap<Class<?>, TypeCode> typeCodes = new HashMap<Class<?>, TypeCode>(primitiveTypeCodeMap); typeCodes.put(String.class, orb.create_wstring_tc(0)); constantTypeCodeMap = typeCodes; } /** * Add mapping for a class. */ public void mapClass(Class cls) throws RMIIIOPViolationException, IRConstructionException { // Just lookup a TypeCode for the class: That will provoke // mapping the class and adding it to the IR. getTypeCode(cls); } /** * Finish the build. */ public void finishBuild() throws IRConstructionException { impl.allDone(); } /** * Return a CORBA reference to this IR. */ public Repository getReference() { return RepositoryHelper.narrow(impl.getReference()); } /** * Deactivate all CORBA objects in this IR. */ public void shutdown() { impl.shutdown(); } /** * Returns the TypeCode suitable for an IDL constant. * * @param cls The Java class denoting the type of the constant. */ private TypeCode getConstantTypeCode(Class cls) throws IRConstructionException { if (cls == null) throw IIOPLogger.ROOT_LOGGER.invalidNullClass(); TypeCode ret = constantTypeCodeMap.get(cls); if (ret == null) throw IIOPLogger.ROOT_LOGGER.badClassForConstant(cls.getName()); return ret; } /** * Returns the TypeCode IDL TypeCodes for parameter, result, attribute * and value member types. * This may provoke a mapping of the class argument. * <p/> * Exception classes map to both values and exceptions. For these, this * method returns the typecode for the value, and you can use the * <code>getExceptionTypeCode</code> TODO method to get the typecode for the * mapping to exception. * * @param cls The Java class denoting the java type. */ private TypeCode getTypeCode(Class cls) throws IRConstructionException, RMIIIOPViolationException { if (cls == null) throw IIOPLogger.ROOT_LOGGER.invalidNullClass(); TypeCode ret = (TypeCode) typeCodeMap.get(cls); if (ret == null) { if (cls == String.class) ret = getJavaLangString().type(); else if (cls == Object.class) ret = getJavaLang_Object().type(); else if (cls == Class.class) ret = getJavaxRmiCORBAClassDesc().type(); else if (cls == java.io.Serializable.class) ret = getJavaIoSerializable().type(); else if (cls == java.io.Externalizable.class) ret = getJavaIoExternalizable().type(); else { // Try adding a mapping of the the class to the IR addClass(cls); // Lookup again, it should be there now. ret = (TypeCode) typeCodeMap.get(cls); if (ret == null) throw IIOPLogger.ROOT_LOGGER.unknownTypeCodeForClass(cls.getName()); else return ret; } typeCodeMap.put(cls, ret); } return ret; } /** * Add a new IDL TypeCode for a mapped class. * * @param cls The Java class denoting the java type. * @param typeCode The IDL type code of the mapped java class. */ private void addTypeCode(Class cls, TypeCode typeCode) throws IRConstructionException { if (cls == null) throw IIOPLogger.ROOT_LOGGER.invalidNullClass(); TypeCode tc = (TypeCode) typeCodeMap.get(cls); if (tc != null) throw IIOPLogger.ROOT_LOGGER.duplicateTypeCodeForClass(cls.getName()); typeCodeMap.put(cls, typeCode); } /** * Get a reference to the special case mapping for java.io.Serializable. * This is according to "Java(TM) Language to IDL Mapping Specification", * section 1.3.10.1 */ private AliasDefImpl getJavaIoSerializable() throws IRConstructionException { if (javaIoSerializable == null) { final String id = "IDL:java/io/Serializable:1.0"; final String name = "Serializable"; final String version = "1.0"; // Get module to add typedef to. ModuleDefImpl m = ensurePackageExists("java.io"); TypeCode typeCode = orb.create_alias_tc(id, name, orb.get_primitive_tc(TCKind.tk_any)); // TypeCode typeCode = new TypeCodeImpl(TCKind._tk_alias, id, name, // new TypeCodeImpl(TCKind.tk_any)); javaIoSerializable = new AliasDefImpl(id, name, version, m, typeCode, impl); m.add(name, javaIoSerializable); } return javaIoSerializable; } /** * Get a reference to the special case mapping for java.io.Externalizable. * This is according to "Java(TM) Language to IDL Mapping Specification", * section 1.3.10.1 */ private AliasDefImpl getJavaIoExternalizable() throws IRConstructionException { if (javaIoExternalizable == null) { final String id = "IDL:java/io/Externalizable:1.0"; final String name = "Externalizable"; final String version = "1.0"; // Get module to add typedef to. ModuleDefImpl m = ensurePackageExists("java.io"); TypeCode typeCode = orb.create_alias_tc(id, name, orb.get_primitive_tc(TCKind.tk_any)); // TypeCode typeCode = new TypeCodeImpl(TCKind._tk_alias, id, name, // new TypeCodeImpl(TCKind.tk_any)); javaIoExternalizable = new AliasDefImpl(id, name, version, m, typeCode, impl); m.add(name, javaIoExternalizable); } return javaIoExternalizable; } /** * Get a reference to the special case mapping for java.lang.Object. * This is according to "Java(TM) Language to IDL Mapping Specification", * section 1.3.10.2 */ private AliasDefImpl getJavaLang_Object() throws IRConstructionException { if (javaLang_Object == null) { final String id = "IDL:java/lang/_Object:1.0"; final String name = "_Object"; final String version = "1.0"; // Get module to add typedef to. ModuleDefImpl m = ensurePackageExists("java.lang"); TypeCode typeCode = orb.create_alias_tc(id, name, orb.get_primitive_tc(TCKind.tk_any)); // TypeCode typeCode = new TypeCodeImpl(TCKind._tk_alias, id, name, // new TypeCodeImpl(TCKind.tk_any)); javaLang_Object = new AliasDefImpl(id, name, version, m, typeCode, impl); m.add(name, javaLang_Object); } return javaLang_Object; } /** * Get a reference to the special case mapping for java.lang.String. * This is according to "Java(TM) Language to IDL Mapping Specification", * section 1.3.5.10 */ private ValueDefImpl getJavaLangString() throws IRConstructionException { if (javaLangString == null) { ModuleDefImpl m = ensurePackageExists("org.omg.CORBA"); ValueDefImpl val = new ValueDefImpl("IDL:omg.org/CORBA/WStringValue:1.0", "WStringValue", "1.0", m, false, false, new String[0], new String[0], orb.get_primitive_tc(TCKind.tk_null), impl); ValueMemberDefImpl vmdi = new ValueMemberDefImpl("IDL:omg.org/CORBA/WStringValue.data:1.0", "data", "1.0", orb.create_wstring_tc(0), true, val, impl); val.add("data", vmdi); m.add("WStringValue", val); javaLangString = val; } return javaLangString; } /** * Get a reference to the special case mapping for java.lang.Class. * This is according to "Java(TM) Language to IDL Mapping Specification", * section 1.3.5.11. */ private ValueDefImpl getJavaxRmiCORBAClassDesc() throws IRConstructionException, RMIIIOPViolationException { if (javaxRmiCORBAClassDesc == null) { // Just map the right value class ValueAnalysis va = ValueAnalysis.getValueAnalysis(javax.rmi.CORBA.ClassDesc.class); ValueDefImpl val = addValue(va); // Warn if it does not conform to the specification. if (!"RMI:javax.rmi.CORBA.ClassDesc:B7C4E3FC9EBDC311:CFBF02CF5294176B".equals(val.id())) IIOPLogger.ROOT_LOGGER.warnClassDescDoesNotConformToSpec(); javaxRmiCORBAClassDesc = val; } return javaxRmiCORBAClassDesc; } /** * Ensure that a package exists in the IR. * This will create modules in the IR as needed. * * @param pkgName The package that needs to be defined as a module in the IR. * @return A reference to the IR module that represents the package. */ private ModuleDefImpl ensurePackageExists(String pkgName) throws IRConstructionException { return ensurePackageExists(impl, "", pkgName); } /** * Ensure that a package exists in the IR. * This will create modules in the IR as needed. * * @param c The container that the remainder of modules should be defined in. * @param previous The IDL module name, from root to <code>c</code>. * @param remainder The java package name, relative to <code>c</code>. * @return A reference to the IR module that represents the package. */ private ModuleDefImpl ensurePackageExists(LocalContainer c, String previous, String remainder) throws IRConstructionException { if ("".equals(remainder)) return (ModuleDefImpl) c; // done int idx = remainder.indexOf('.'); String base; if (idx == -1) base = remainder; else base = remainder.substring(0, idx); base = Util.javaToIDLName(base); if (previous.equals("")) previous = base; else previous = previous + "/" + base; if (idx == -1) remainder = ""; else remainder = remainder.substring(idx + 1); LocalContainer next = null; LocalContained contained = (LocalContained) c._lookup(base); if (contained instanceof LocalContainer) next = (LocalContainer) contained; else if (contained != null) throw IIOPLogger.ROOT_LOGGER.collisionWhileCreatingPackage(); if (next == null) { String id = "IDL:" + previous + ":1.0"; // Create module ModuleDefImpl m = new ModuleDefImpl(id, base, "1.0", c, impl); c.add(base, m); if (idx == -1) return m; // done next = (LocalContainer) c._lookup(base); // Better be there now... } else // Check that next _is_ a module if (next.def_kind() != DefinitionKind.dk_Module) throw IIOPLogger.ROOT_LOGGER.collisionWhileCreatingPackage(); return ensurePackageExists(next, previous, remainder); } /** * Add a set of constants to a container (interface or value class). */ private void addConstants(LocalContainer container, ContainerAnalysis ca) throws RMIIIOPViolationException, IRConstructionException { ConstantAnalysis[] consts = ca.getConstants(); for (int i = 0; i < consts.length; ++i) { ConstantDefImpl cDef; String cid = ca.getMemberRepositoryId(consts[i].getJavaName()); String cName = consts[i].getIDLName(); Class cls = consts[i].getType(); TypeCode typeCode = getConstantTypeCode(cls); Any value = orb.create_any(); consts[i].insertValue(value); cDef = new ConstantDefImpl(cid, cName, "1.0", typeCode, value, container, impl); container.add(cName, cDef); } } /** * Add a set of attributes to a container (interface or value class). */ private void addAttributes(LocalContainer container, ContainerAnalysis ca) throws RMIIIOPViolationException, IRConstructionException { AttributeAnalysis[] attrs = ca.getAttributes(); for (int i = 0; i < attrs.length; ++i) { AttributeDefImpl aDef; String aid = ca.getMemberRepositoryId(attrs[i].getJavaName()); String aName = attrs[i].getIDLName(); Class cls = attrs[i].getCls(); TypeCode typeCode = getTypeCode(cls); aDef = new AttributeDefImpl(aid, aName, "1.0", attrs[i].getMode(), typeCode, container, impl); container.add(aName, aDef); } } /** * Add a set of operations to a container (interface or value class). */ private void addOperations(LocalContainer container, ContainerAnalysis ca) throws RMIIIOPViolationException, IRConstructionException { OperationAnalysis[] ops = ca.getOperations(); for (int i = 0; i < ops.length; ++i) { OperationDefImpl oDef; String oName = ops[i].getIDLName(); String oid = ca.getMemberRepositoryId(oName); Class cls = ops[i].getReturnType(); TypeCode typeCode = getTypeCode(cls); ParameterAnalysis[] ps = ops[i].getParameters(); ParameterDescription[] params = new ParameterDescription[ps.length]; for (int j = 0; j < ps.length; ++j) { params[j] = new ParameterDescription(ps[j].getIDLName(), getTypeCode(ps[j].getCls()), null, // filled in later ParameterMode.PARAM_IN); } ExceptionAnalysis[] exc = ops[i].getMappedExceptions(); ExceptionDef[] exceptions = new ExceptionDef[exc.length]; for (int j = 0; j < exc.length; ++j) { ExceptionDefImpl e = addException(exc[j]); exceptions[j] = ExceptionDefHelper.narrow(e.getReference()); } oDef = new OperationDefImpl(oid, oName, "1.0", container, typeCode, params, exceptions, impl); container.add(oName, oDef); } } /** * Add a set of interfaces to the IR. * * @return An array of the IR IDs of the interfaces. */ private String[] addInterfaces(ContainerAnalysis ca) throws RMIIIOPViolationException, IRConstructionException { InterfaceAnalysis[] interfaces = ca.getInterfaces(); List base_interfaces = new ArrayList(); for (int i = 0; i < interfaces.length; ++i) { InterfaceDefImpl idi = addInterface(interfaces[i]); base_interfaces.add(idi.id()); } String[] strArr = new String[base_interfaces.size()]; return (String[]) base_interfaces.toArray(strArr); } /** * Add a set of abstract valuetypes to the IR. * * @return An array of the IR IDs of the abstract valuetypes. */ private String[] addAbstractBaseValuetypes(ContainerAnalysis ca) throws RMIIIOPViolationException, IRConstructionException { ValueAnalysis[] abstractValuetypes = ca.getAbstractBaseValuetypes(); List abstract_base_valuetypes = new ArrayList(); for (int i = 0; i < abstractValuetypes.length; ++i) { ValueDefImpl vdi = addValue(abstractValuetypes[i]); abstract_base_valuetypes.add(vdi.id()); } String[] strArr = new String[abstract_base_valuetypes.size()]; return (String[]) abstract_base_valuetypes.toArray(strArr); } /** * Map the class and add its IIOP mapping to the repository. */ private void addClass(Class cls) throws RMIIIOPViolationException, IRConstructionException { if (cls.isPrimitive()) return; // No need to add primitives. if (cls.isArray()) { // Add array mapping addArray(cls); } else if (cls.isInterface()) { if (!RmiIdlUtil.isAbstractValueType(cls)) { // Analyse the interface InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls); // Add analyzed interface (which may be abstract) addInterface(ia); } else { // Analyse the value ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls); // Add analyzed value addValue(va); } } else if (Exception.class.isAssignableFrom(cls)) { // Exception type. // Analyse the exception ExceptionAnalysis ea = ExceptionAnalysis.getExceptionAnalysis(cls); // Add analyzed exception addException(ea); } else { // Got to be a value type. // Analyse the value ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls); // Add analyzed value addValue(va); } } /** * Add an array. */ private ValueBoxDefImpl addArray(Class cls) throws RMIIIOPViolationException, IRConstructionException { if (!cls.isArray()) throw IIOPLogger.ROOT_LOGGER.classIsNotArray(cls.getName()); ValueBoxDefImpl vbDef; // Lookup: Has it already been added? vbDef = (ValueBoxDefImpl) arrayMap.get(cls); if (vbDef != null) return vbDef; // Yes, just return it. int dimensions = 0; Class compType = cls; do { compType = compType.getComponentType(); ++dimensions; } while (compType.isArray()); String typeName; String moduleName; TypeCode typeCode; if (compType.isPrimitive()) { if (compType == Boolean.TYPE) { typeName = "boolean"; typeCode = orb.get_primitive_tc(TCKind.tk_boolean); } else if (compType == Character.TYPE) { typeName = "wchar"; typeCode = orb.get_primitive_tc(TCKind.tk_wchar); } else if (compType == Byte.TYPE) { typeName = "octet"; typeCode = orb.get_primitive_tc(TCKind.tk_octet); } else if (compType == Short.TYPE) { typeName = "short"; typeCode = orb.get_primitive_tc(TCKind.tk_short); } else if (compType == Integer.TYPE) { typeName = "long"; typeCode = orb.get_primitive_tc(TCKind.tk_long); } else if (compType == Long.TYPE) { typeName = "long_long"; typeCode = orb.get_primitive_tc(TCKind.tk_longlong); } else if (compType == Float.TYPE) { typeName = "float"; typeCode = orb.get_primitive_tc(TCKind.tk_float); } else if (compType == Double.TYPE) { typeName = "double"; typeCode = orb.get_primitive_tc(TCKind.tk_double); } else { throw IIOPLogger.ROOT_LOGGER.unknownPrimitiveType(compType.getName()); } moduleName = "org.omg.boxedRMI"; } else { typeCode = getTypeCode(compType); // map the component type. if (compType == String.class) typeName = getJavaLangString().name(); else if (compType == Object.class) typeName = getJavaLang_Object().name(); else if (compType == Class.class) typeName = getJavaxRmiCORBAClassDesc().name(); else if (compType == java.io.Serializable.class) typeName = getJavaIoSerializable().name(); else if (compType == java.io.Externalizable.class) typeName = getJavaIoExternalizable().name(); else if (compType.isInterface() && !RmiIdlUtil.isAbstractValueType(compType)) typeName = ((InterfaceDefImpl) interfaceMap.get(compType)).name(); else if (Exception.class.isAssignableFrom(compType)) // exception type typeName = ((ExceptionDefImpl) exceptionMap.get(compType)).name(); else // must be value type typeName = ((ValueDefImpl) valueMap.get(compType)).name(); moduleName = "org.omg.boxedRMI." + compType.getPackage().getName(); } // Get module to add array to. ModuleDefImpl m = ensurePackageExists(moduleName); // Create an array of the types for the dimensions Class[] types = new Class[dimensions]; types[dimensions - 1] = cls; for (int i = dimensions - 2; i >= 0; --i) types[i] = types[i + 1].getComponentType(); // Create boxed sequences for all dimensions. for (int i = 0; i < dimensions; ++i) { Class type = types[i]; typeCode = orb.create_sequence_tc(0, typeCode); vbDef = (ValueBoxDefImpl) arrayMap.get(type); if (vbDef == null) { String id = Util.getIRIdentifierOfClass(type); SequenceDefImpl sdi = new SequenceDefImpl(typeCode, impl); String name = "seq" + (i + 1) + "_" + typeName; // TypeCode boxTypeCode = new TypeCodeImpl(TCKind._tk_value_box, // id, name, typeCode); TypeCode boxTypeCode = orb.create_value_box_tc(id, name, typeCode); vbDef = new ValueBoxDefImpl(id, name, "1.0", m, boxTypeCode, impl); addTypeCode(type, vbDef.type()); m.add(name, vbDef); impl.putSequenceImpl(id, typeCode, sdi, vbDef); arrayMap.put(type, vbDef); // Remember we mapped this. typeCode = boxTypeCode; } else typeCode = vbDef.type(); } // Return the box of highest dimension. return vbDef; } /** * Add an interface. */ private InterfaceDefImpl addInterface(InterfaceAnalysis ia) throws RMIIIOPViolationException, IRConstructionException { InterfaceDefImpl iDef; Class cls = ia.getCls(); // Lookup: Has it already been added? iDef = (InterfaceDefImpl) interfaceMap.get(cls); if (iDef != null) return iDef; // Yes, just return it. // Get module to add interface to. ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName()); // Add superinterfaces String[] base_interfaces = addInterfaces(ia); // Create the interface String base = cls.getName(); base = base.substring(base.lastIndexOf('.') + 1); base = Util.javaToIDLName(base); iDef = new InterfaceDefImpl(ia.getRepositoryId(), base, "1.0", m, base_interfaces, impl); addTypeCode(cls, iDef.type()); m.add(base, iDef); interfaceMap.put(cls, iDef); // Remember we mapped this. // Fill in constants addConstants(iDef, ia); // Add attributes addAttributes(iDef, ia); // Fill in operations addOperations(iDef, ia); return iDef; } /** * Add a value type. */ private ValueDefImpl addValue(ValueAnalysis va) throws RMIIIOPViolationException, IRConstructionException { ValueDefImpl vDef; Class cls = va.getCls(); // Lookup: Has it already been added? vDef = (ValueDefImpl) valueMap.get(cls); if (vDef != null) return vDef; // Yes, just return it. // Get module to add value to. ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName()); // Add implemented interfaces String[] supported_interfaces = addInterfaces(va); // Add abstract base valuetypes String[] abstract_base_valuetypes = addAbstractBaseValuetypes(va); // Add superclass ValueDefImpl superValue = null; ValueAnalysis superAnalysis = va.getSuperAnalysis(); if (superAnalysis != null) superValue = addValue(superAnalysis); // Create the value String base = cls.getName(); base = base.substring(base.lastIndexOf('.') + 1); base = Util.javaToIDLName(base); TypeCode baseTypeCode; if (superValue == null) baseTypeCode = orb.get_primitive_tc(TCKind.tk_null); else baseTypeCode = superValue.type(); vDef = new ValueDefImpl(va.getRepositoryId(), base, "1.0", m, va.isAbstractValue(), va.isCustom(), supported_interfaces, abstract_base_valuetypes, baseTypeCode, impl); addTypeCode(cls, vDef.type()); m.add(base, vDef); valueMap.put(cls, vDef); // Remember we mapped this. // Fill in constants. addConstants(vDef, va); // Add value members ValueMemberAnalysis[] vmas = va.getMembers(); for (int i = 0; i < vmas.length; ++i) { ValueMemberDefImpl vmDef; String vmid = va.getMemberRepositoryId(vmas[i].getJavaName()); String vmName = vmas[i].getIDLName(); Class vmCls = vmas[i].getCls(); TypeCode typeCode = getTypeCode(vmCls); boolean vmPublic = vmas[i].isPublic(); vmDef = new ValueMemberDefImpl(vmid, vmName, "1.0", typeCode, vmPublic, vDef, impl); vDef.add(vmName, vmDef); } // Add attributes addAttributes(vDef, va); // TODO: Fill in operations. return vDef; } /** * Add an exception type. */ private ExceptionDefImpl addException(ExceptionAnalysis ea) throws RMIIIOPViolationException, IRConstructionException { ExceptionDefImpl eDef; Class cls = ea.getCls(); // Lookup: Has it already been added? eDef = (ExceptionDefImpl) exceptionMap.get(cls); if (eDef != null) return eDef; // Yes, just return it. // 1.3.7.1: map to value ValueDefImpl vDef = addValue(ea); // 1.3.7.2: map to exception ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName()); String base = cls.getName(); base = base.substring(base.lastIndexOf('.') + 1); if (base.endsWith("Exception")) base = base.substring(0, base.length() - 9); base = Util.javaToIDLName(base + "Ex"); StructMember[] members = new StructMember[1]; members[0] = new StructMember("value", vDef.type(), null/*ignored*/); TypeCode typeCode = orb.create_exception_tc(ea.getExceptionRepositoryId(), base, members); eDef = new ExceptionDefImpl(ea.getExceptionRepositoryId(), base, "1.0", typeCode, vDef, m, impl); m.add(base, eDef); exceptionMap.put(cls, eDef); // Remember we mapped this. return eDef; } // Inner classes ------------------------------------------------- }
34,235
35.228571
108
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/RepositoryImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.omg.CORBA.ArrayDef; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedHelper; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.FixedDef; import org.omg.CORBA.IRObject; import org.omg.CORBA.ORB; import org.omg.CORBA.PrimitiveDef; import org.omg.CORBA.Repository; import org.omg.CORBA.RepositoryOperations; import org.omg.CORBA.RepositoryPOATie; import org.omg.CORBA.SequenceDef; import org.omg.CORBA.StringDef; import org.omg.CORBA.TypeCode; import org.omg.CORBA.WstringDef; import org.omg.PortableServer.POA; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * An Interface Repository. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ class RepositoryImpl extends ContainerImpl implements RepositoryOperations, LocalContainer { public RepositoryImpl(ORB orb, POA poa, String name) { super(DefinitionKind.dk_Repository, null); this.orb = orb; this.poa = poa; oid = name.getBytes(StandardCharsets.UTF_8); oidPrefix = name + ":"; anonOidPrefix = oidPrefix + "anon"; repository = this; } public IRObject getReference() { if (ref == null) { ref = org.omg.CORBA.RepositoryHelper.narrow( servantToReference(new RepositoryPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { super.allDone(); // call allDone() for all our sequences Iterator iter = sequenceMap.values().iterator(); while (iter.hasNext()) ((SequenceDefImpl) iter.next()).allDone(); } public void shutdown() { // shutdown all anonymous IR objects in this IR for (long i = 1; i < nextPOAId; i++) { try { getPOA().deactivate_object(getAnonymousObjectId(i)); } catch (org.omg.CORBA.UserException ex) { IIOPLogger.ROOT_LOGGER.warnCouldNotDeactivateAnonIRObject(ex); } } // shutdown this IR's top-level container super.shutdown(); } // Repository implementation ------------------------------------- public Contained lookup_id(String search_id) { LocalContained c = _lookup_id(search_id); if (c == null) return null; return ContainedHelper.narrow(c.getReference()); } public TypeCode get_canonical_typecode(TypeCode tc) { // TODO return null; } public PrimitiveDef get_primitive(org.omg.CORBA.PrimitiveKind kind) { // TODO return null; } public StringDef create_string(int bound) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public WstringDef create_wstring(int bound) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public SequenceDef create_sequence(int bound, org.omg.CORBA.IDLType element_type) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ArrayDef create_array(int length, org.omg.CORBA.IDLType element_type) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public FixedDef create_fixed(short digits, short scale) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- /** * The ORB that I use. */ ORB orb = null; /** * The POA that I use. */ POA poa = null; /** * The POA object ID of this repository. */ private byte[] oid = null; /** * Prefix for POA object IDs of IR objects in this repository. */ private String oidPrefix = null; /** * Prefix for POA object IDs of "anonymous" IR objects in this repository. */ private String anonOidPrefix = null; /** * Maps typecodes of sequences defined in this IR to the sequences. */ Map sequenceMap = new HashMap(); /** * Maps repository IDs of sequences defined in this IR to the sequences. */ Map sequenceIdMap = new HashMap(); LocalContained _lookup_id(String search_id) { // mapping of arrays are special if (search_id.startsWith("RMI:[")) return (ValueBoxDefImpl) sequenceIdMap.get(search_id); // convert id String name = scopedName(search_id); // look it up if converted id not null //return (name == null) ? null : _lookup(name); LocalContained ret = (name == null) ? null : _lookup(name); return ret; } SequenceDefImpl getSequenceImpl(TypeCode typeCode) { return (SequenceDefImpl) sequenceMap.get(typeCode); } void putSequenceImpl(String id, TypeCode typeCode, SequenceDefImpl sequence, ValueBoxDefImpl valueBox) { sequenceIdMap.put(id, valueBox); sequenceMap.put(typeCode, sequence); } String getObjectIdPrefix() { return oidPrefix; } // Protected ----------------------------------------------------- /** * Return the POA object ID of this IR object. */ protected byte[] getObjectId() { return (byte[]) oid.clone(); } /** * Generate the ID of the n-th "anonymous" object created in this IR. */ protected byte[] getAnonymousObjectId(long n) { String s = anonOidPrefix + Long.toString(n); return s.getBytes(StandardCharsets.UTF_8); } /** * The next "anonymous" POA object ID. * While contained IR objects can generate a sensible ID from their * repository ID, non-contained objects use this method to get an * ID that is unique within the IR. */ protected byte[] getNextObjectId() { return getAnonymousObjectId(nextPOAId++); } // Private ------------------------------------------------------- /** * My CORBA reference. */ private Repository ref = null; /** * The next "anonymous" POA object ID. */ private long nextPOAId = 1; /** * Convert a repository ID to an IDL scoped name. * Returns <code>null</code> if the ID cannot be understood. */ private String scopedName(String id) { if (id == null) return null; if (id.startsWith("IDL:")) { // OMG IDL format // Check for base types if ("IDL:omg.org/CORBA/Object:1.0".equals(id) || "IDL:omg.org/CORBA/ValueBase:1.0".equals(id)) return null; // Get 2nd component of ID int idx2 = id.indexOf(':', 4); // 2nd colon if (idx2 == -1) return null; // invalid ID, version part missing String base = id.substring(4, id.indexOf(':', 4)); // Check special prefixes if (base.startsWith("omg.org")) base = "org/omg" + base.substring(7); if (base.startsWith("w3c.org")) base = "org/w3c" + base.substring(7); // convert '/' to "::" StringBuffer b = new StringBuffer(); for (int i = 0; i < base.length(); ++i) { char c = base.charAt(i); if (c != '/') b.append(c); else b.append("::"); } return b.toString(); } else if (id.startsWith("RMI:")) { // RMI hashed format // Get 2nd component of ID int idx2 = id.indexOf(':', 4); // 2nd colon if (idx2 == -1) return null; // invalid ID, version part missing String base = id.substring(4, id.indexOf(':', 4)); // convert '.' to "::" StringBuffer b = new StringBuffer(); for (int i = 0; i < base.length(); ++i) { char c = base.charAt(i); if (c != '.') b.append(c); else b.append("::"); } return b.toString(); } else return null; } // Inner classes ------------------------------------------------- }
9,441
28.785489
92
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/ValueDefImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.AliasDef; import org.omg.CORBA.Any; import org.omg.CORBA.AttributeDef; import org.omg.CORBA.AttributeDescription; import org.omg.CORBA.AttributeMode; import org.omg.CORBA.ConstantDef; import org.omg.CORBA.Contained; import org.omg.CORBA.ContainedPackage.Description; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.EnumDef; import org.omg.CORBA.ExceptionDef; import org.omg.CORBA.IDLType; import org.omg.CORBA.IRObject; import org.omg.CORBA.Initializer; import org.omg.CORBA.InterfaceDef; import org.omg.CORBA.InterfaceDefHelper; import org.omg.CORBA.ModuleDef; import org.omg.CORBA.NativeDef; import org.omg.CORBA.OperationDef; import org.omg.CORBA.OperationDescription; import org.omg.CORBA.OperationMode; import org.omg.CORBA.ParameterDescription; import org.omg.CORBA.StructDef; import org.omg.CORBA.StructMember; import org.omg.CORBA.TCKind; import org.omg.CORBA.TypeCode; import org.omg.CORBA.TypeCodePackage.BadKind; import org.omg.CORBA.UnionDef; import org.omg.CORBA.UnionMember; import org.omg.CORBA.VM_ABSTRACT; import org.omg.CORBA.VM_CUSTOM; import org.omg.CORBA.VM_NONE; import org.omg.CORBA.ValueBoxDef; import org.omg.CORBA.ValueDef; import org.omg.CORBA.ValueDefHelper; import org.omg.CORBA.ValueDefOperations; import org.omg.CORBA.ValueDefPOATie; import org.omg.CORBA.ValueDefPackage.FullValueDescription; import org.omg.CORBA.ValueDescription; import org.omg.CORBA.ValueDescriptionHelper; import org.omg.CORBA.ValueMember; import org.omg.CORBA.ValueMemberDef; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Interface IR object. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> * @version $Revision: 81018 $ */ class ValueDefImpl extends ContainedImpl implements ValueDefOperations, LocalContainer, LocalContainedIDLType { // Constructors -------------------------------------------------- ValueDefImpl(String id, String name, String version, LocalContainer defined_in, boolean is_abstract, boolean is_custom, String[] supported_interfaces, String[] abstract_base_valuetypes, TypeCode baseValueTypeCode, RepositoryImpl repository) { super(id, name, version, defined_in, DefinitionKind.dk_Value, repository); this.is_abstract = is_abstract; this.is_custom = is_custom; this.supported_interfaces = supported_interfaces; this.abstract_base_valuetypes = abstract_base_valuetypes; this.baseValueTypeCode = baseValueTypeCode; this.delegate = new ContainerImplDelegate(this); } // Public -------------------------------------------------------- // LocalContainer implementation --------------------------------- public LocalContained _lookup(String search_name) { return delegate._lookup(search_name); } public LocalContained[] _contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate._contents(limit_type, exclude_inherited); } public LocalContained[] _lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate._lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public void add(String name, LocalContained contained) throws IRConstructionException { delegate.add(name, contained); } // LocalIRObject implementation --------------------------------- public IRObject getReference() { if (ref == null) { ref = ValueDefHelper.narrow( servantToReference(new ValueDefPOATie(this))); } return ref; } public void allDone() throws IRConstructionException { getReference(); delegate.allDone(); if (baseValueTypeCode != null && baseValueTypeCode.kind() != TCKind.tk_null) { try { baseValue = baseValueTypeCode.id(); } catch (BadKind ex) { throw IIOPLogger.ROOT_LOGGER.badKindForSuperValueType(id()); } Contained c = repository.lookup_id(baseValue); base_value_ref = ValueDefHelper.narrow(c); } else baseValue = "IDL:omg.org/CORBA/ValueBase:1.0"; // TODO: is this right? // Resolve supported interfaces supported_interfaces_ref = new InterfaceDef[supported_interfaces.length]; for (int i = 0; i < supported_interfaces.length; ++i) { InterfaceDef iDef = InterfaceDefHelper.narrow( repository.lookup_id(supported_interfaces[i])); if (iDef == null) throw IIOPLogger.ROOT_LOGGER.errorResolvingRefToImplementedInterface(id(), supported_interfaces[i]); supported_interfaces_ref[i] = iDef; } // Resolve abstract base valuetypes abstract_base_valuetypes_ref = new ValueDef[abstract_base_valuetypes.length]; for (int i = 0; i < abstract_base_valuetypes.length; ++i) { ValueDef vDef = ValueDefHelper.narrow( repository.lookup_id(abstract_base_valuetypes[i])); if (vDef == null) throw IIOPLogger.ROOT_LOGGER.errorResolvingRefToAbstractValuetype(id(), abstract_base_valuetypes[i]); abstract_base_valuetypes_ref[i] = vDef; } } public void shutdown() { delegate.shutdown(); super.shutdown(); } // ContainerOperations implementation ---------------------------- public Contained lookup(String search_name) { return delegate.lookup(search_name); } public Contained[] contents(DefinitionKind limit_type, boolean exclude_inherited) { return delegate.contents(limit_type, exclude_inherited); } public Contained[] lookup_name(String search_name, int levels_to_search, DefinitionKind limit_type, boolean exclude_inherited) { return delegate.lookup_name(search_name, levels_to_search, limit_type, exclude_inherited); } public org.omg.CORBA.ContainerPackage.Description[] describe_contents(DefinitionKind limit_type, boolean exclude_inherited, int max_returned_objs) { return delegate.describe_contents(limit_type, exclude_inherited, max_returned_objs); } public ModuleDef create_module(String id, String name, String version) { return delegate.create_module(id, name, version); } public ConstantDef create_constant(String id, String name, String version, IDLType type, Any value) { return delegate.create_constant(id, name, version, type, value); } public StructDef create_struct(String id, String name, String version, StructMember[] members) { return delegate.create_struct(id, name, version, members); } public UnionDef create_union(String id, String name, String version, IDLType discriminator_type, UnionMember[] members) { return delegate.create_union(id, name, version, discriminator_type, members); } public EnumDef create_enum(String id, String name, String version, String[] members) { return delegate.create_enum(id, name, version, members); } public AliasDef create_alias(String id, String name, String version, IDLType original_type) { return delegate.create_alias(id, name, version, original_type); } public InterfaceDef create_interface(String id, String name, String version, InterfaceDef[] base_interfaces, boolean is_abstract) { return delegate.create_interface(id, name, version, base_interfaces, is_abstract); } public ValueDef create_value(String id, String name, String version, boolean is_custom, boolean is_abstract, ValueDef base_value, boolean is_truncatable, ValueDef[] abstract_base_values, InterfaceDef[] supported_interfaces, Initializer[] initializers) { return delegate.create_value(id, name, version, is_custom, is_abstract, base_value, is_truncatable, abstract_base_values, supported_interfaces, initializers); } public ValueBoxDef create_value_box(String id, String name, String version, IDLType original_type_def) { return delegate.create_value_box(id, name, version, original_type_def); } public ExceptionDef create_exception(String id, String name, String version, StructMember[] members) { return delegate.create_exception(id, name, version, members); } public NativeDef create_native(String id, String name, String version) { return delegate.create_native(id, name, version); } // ValueDefOperations implementation ------------------------- public InterfaceDef[] supported_interfaces() { return supported_interfaces_ref; } public void supported_interfaces(InterfaceDef[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public Initializer[] initializers() { // We do not (currently) map constructors, as that is optional according // to the specification. return new Initializer[0]; } public void initializers(Initializer[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ValueDef base_value() { return base_value_ref; } public void base_value(ValueDef arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public ValueDef[] abstract_base_values() { return abstract_base_valuetypes_ref; } public void abstract_base_values(ValueDef[] arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_abstract() { return is_abstract; } public void is_abstract(boolean arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_custom() { return is_custom; } public void is_custom(boolean arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_truncatable() { return false; } public void is_truncatable(boolean arg) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public boolean is_a(String id) { // TODO return id().equals(id); } public FullValueDescription describe_value() { if (fullValueDescription != null) return fullValueDescription; // Has to create the FullValueDescription // TODO OperationDescription[] operations = new OperationDescription[0]; AttributeDescription[] attributes = new AttributeDescription[0]; String defined_in_id = "IDL:Global:1.0"; if (defined_in instanceof org.omg.CORBA.ContainedOperations) defined_in_id = ((org.omg.CORBA.ContainedOperations) defined_in).id(); fullValueDescription = new FullValueDescription(name, id, is_abstract, is_custom, defined_in_id, version, operations, attributes, getValueMembers(), new Initializer[0], // TODO supported_interfaces, abstract_base_valuetypes, false, baseValue, typeCode); return fullValueDescription; } public ValueMemberDef create_value_member(String id, String name, String version, IDLType type, short access) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public AttributeDef create_attribute(String id, String name, String version, IDLType type, AttributeMode mode) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } public OperationDef create_operation(String id, String name, String version, IDLType result, OperationMode mode, ParameterDescription[] params, ExceptionDef[] exceptions, String[] contexts) { throw IIOPLogger.ROOT_LOGGER.cannotChangeRMIIIOPMapping(); } // IDLTypeOperations implementation ------------------------------ public TypeCode type() { if (typeCode == null) { short modifier = VM_NONE.value; if (is_custom) modifier = VM_CUSTOM.value; else if (is_abstract) modifier = VM_ABSTRACT.value; typeCode = getORB().create_value_tc(id, name, modifier, baseValueTypeCode, getValueMembersForTypeCode()); } return typeCode; } // ContainedImpl implementation ---------------------------------- public Description describe() { String defined_in_id = "IR"; if (defined_in instanceof org.omg.CORBA.ContainedOperations) defined_in_id = ((org.omg.CORBA.ContainedOperations) defined_in).id(); ValueDescription md = new ValueDescription(name, id, is_abstract, is_custom, defined_in_id, version, supported_interfaces, abstract_base_valuetypes, false, baseValue); Any any = getORB().create_any(); ValueDescriptionHelper.insert(any, md); return new Description(DefinitionKind.dk_Value, any); } // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- /** * My delegate for Container functionality. */ private ContainerImplDelegate delegate; /** * My CORBA reference. */ private ValueDef ref = null; /** * Flag that I am abstract. */ private boolean is_abstract; /** * Flag that I use custom marshaling. */ private boolean is_custom; /** * IDs of my implemented interfaces. */ private String[] supported_interfaces; /** * CORBA references to my implemented interfaces. */ private InterfaceDef[] supported_interfaces_ref; /** * IR ID of my base value (the class I extend from). */ private String baseValue; /** * TypeCode of my base value (the class I extend from). */ private TypeCode baseValueTypeCode; /** * CORBA reference to my base type. */ private ValueDef base_value_ref; /** * IDs of my abstract base valuetypes. */ private String[] abstract_base_valuetypes; /** * CORBA references to my abstract base valuetypes. */ private ValueDef[] abstract_base_valuetypes_ref; /** * My cached TypeCode. */ private TypeCode typeCode; /** * My Cached ValueMember[]. */ private ValueMember[] valueMembers; /** * My cached FullValueDescription. */ private FullValueDescription fullValueDescription; /** * Create the valueMembers array, and return it. */ private ValueMember[] getValueMembers() { if (valueMembers != null) return valueMembers; LocalContained[] c = _contents(DefinitionKind.dk_ValueMember, false); valueMembers = new ValueMember[c.length]; for (int i = 0; i < c.length; ++i) { ValueMemberDefImpl vmdi = (ValueMemberDefImpl) c[i]; valueMembers[i] = new ValueMember(vmdi.name(), vmdi.id(), ((LocalContained) vmdi.defined_in).id(), vmdi.version(), vmdi.type(), vmdi.type_def(), vmdi.access()); } return valueMembers; } /** * Create a valueMembers array for TypeCode creation only, and return it. */ private ValueMember[] getValueMembersForTypeCode() { LocalContained[] c = _contents(DefinitionKind.dk_ValueMember, false); ValueMember[] vms = new ValueMember[c.length]; for (int i = 0; i < c.length; ++i) { ValueMemberDefImpl vmdi = (ValueMemberDefImpl) c[i]; vms[i] = new ValueMember(vmdi.name(), null, // ignore id null, // ignore defined_in null, // ignore version vmdi.type(), null, // ignore type_def vmdi.access()); } return vms; } // Inner classes ------------------------------------------------- }
18,776
33.39011
117
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/rmi/ir/IRObjectImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.rmi.ir; import org.omg.CORBA.DefinitionKind; import org.omg.CORBA.IRObject; import org.omg.CORBA.IRObjectOperations; import org.omg.CORBA.ORB; import org.omg.CORBA.UserException; import org.omg.PortableServer.POA; import org.omg.PortableServer.Servant; import org.omg.PortableServer.POAPackage.ObjectAlreadyActive; import org.omg.PortableServer.POAPackage.ObjectNotActive; import org.omg.PortableServer.POAPackage.ServantAlreadyActive; import org.omg.PortableServer.POAPackage.WrongPolicy; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Abstract base class for all IR object implementations. * * @author <a href="mailto:osh@sparre.dk">Ole Husgaard</a> */ abstract class IRObjectImpl implements IRObjectOperations { protected RepositoryImpl repository; protected final DefinitionKind def_kind; IRObjectImpl(DefinitionKind def_kind, RepositoryImpl repository) { this.def_kind = def_kind; this.repository = repository; } public DefinitionKind def_kind() { return def_kind; } public void destroy() { throw IIOPLogger.ROOT_LOGGER.cannotDestroyRMIIIOPMapping(); } public abstract IRObject getReference(); public void allDone() throws IRConstructionException { getReference(); } /** * Unexport this object. */ public void shutdown() { POA poa = getPOA(); try { poa.deactivate_object(poa.reference_to_id(getReference())); } catch (UserException ex) { IIOPLogger.ROOT_LOGGER.warnCouldNotDeactivateIRObject(ex); } } public RepositoryImpl getRepository() { return repository; } /** * Return the ORB for this IRObject. */ protected ORB getORB() { return repository.orb; } /** * Return the POA for this IRObject. */ protected POA getPOA() { return repository.poa; } /** * Return the POA object ID of this IR object. */ protected abstract byte[] getObjectId(); /** * Convert a servant to a reference. */ protected org.omg.CORBA.Object servantToReference(Servant servant) { byte[] id = getObjectId(); try { repository.poa.activate_object_with_id(id, servant); org.omg.CORBA.Object ref = repository.poa.id_to_reference(id); return ref; } catch (WrongPolicy ex) { IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex); } catch (ServantAlreadyActive ex) { IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex); } catch (ObjectAlreadyActive ex) { IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex); } catch (ObjectNotActive ex) { IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex); } return null; } }
4,043
31.095238
96
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/security/SocketFactoryBase.java
/* * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.security; import com.sun.corba.se.impl.orbutil.ORBConstants; import com.sun.corba.se.pept.transport.Acceptor; import com.sun.corba.se.spi.orb.ORB; import com.sun.corba.se.spi.transport.ORBSocketFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.security.PrivilegedAction; public abstract class SocketFactoryBase implements ORBSocketFactory { protected ORB orb; private static final boolean keepAlive; static { keepAlive = java.security.AccessController.doPrivileged( new PrivilegedAction<Boolean>() { @Override public Boolean run () { String value = System.getProperty("com.sun.CORBA.transport.enableTcpKeepAlive"); if (value != null) return !"false".equalsIgnoreCase(value); return Boolean.FALSE; } }); } @Override public void setORB(ORB orb) { this.orb = orb; } public ServerSocket createServerSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { ServerSocketChannel serverSocketChannel = null; ServerSocket serverSocket = null; if (orb.getORBData().acceptorSocketType().equals(ORBConstants.SOCKETCHANNEL)) { serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); } else { serverSocket = new ServerSocket(); } serverSocket.bind(inetSocketAddress); return serverSocket; } public Socket createSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { SocketChannel socketChannel = null; Socket socket = null; if (orb.getORBData().connectionSocketType().equals(ORBConstants.SOCKETCHANNEL)) { socketChannel = SocketChannel.open(inetSocketAddress); socket = socketChannel.socket(); } else { socket = new Socket(inetSocketAddress.getHostName(), inetSocketAddress.getPort()); } // Disable Nagle's algorithm (i.e., always send immediately). socket.setTcpNoDelay(true); if (keepAlive) socket.setKeepAlive(true); return socket; } public void setAcceptedSocketOptions(Acceptor acceptor, ServerSocket serverSocket, Socket socket) throws SocketException { // Disable Nagle's algorithm (i.e., always send immediately). socket.setTcpNoDelay(true); if (keepAlive) socket.setKeepAlive(true); } }
4,092
37.252336
126
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/security/SSLSocketFactory.java
/* * Copyright 2016 Red Hat, Inc. * * 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.wildfly.iiop.openjdk.security; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.security.AccessController; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import com.sun.corba.se.spi.orb.ORB; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.security.manager.WildFlySecurityManager; /** * A {@link com.sun.corba.se.spi.transport.ORBSocketFactory} implementation that uses Elytron supplied {@link SSLContext}s * to create client and server side SSL sockets. * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class SSLSocketFactory extends SocketFactoryBase { private static final String SSL_CONTEXT_CAPABILITY = "org.wildfly.security.ssl-context"; private static final RuntimeCapability<Void> SSL_CONTEXT_RUNTIME_CAPABILITY = RuntimeCapability .Builder.of(SSL_CONTEXT_CAPABILITY, true, SSLContext.class) .build(); private static String serverSSLContextName = null; public static void setServerSSLContextName(final String serverSSLContextName) { SSLSocketFactory.serverSSLContextName = serverSSLContextName; } private static String clientSSLContextName = null; public static void setClientSSLContextName(final String clientSSLContextName) { SSLSocketFactory.clientSSLContextName = clientSSLContextName; } private SSLContext serverSSLContext = null; private SSLContext clientSSLContext = null; @Override public void setORB(ORB orb) { super.setORB(orb); ServiceContainer container = this.currentServiceContainer(); final ServiceName serverContextServiceName = SSL_CONTEXT_RUNTIME_CAPABILITY.getCapabilityServiceName(serverSSLContextName); this.serverSSLContext = (SSLContext) container.getRequiredService(serverContextServiceName).getValue(); final ServiceName clientContextServiceName = SSL_CONTEXT_RUNTIME_CAPABILITY.getCapabilityServiceName(clientSSLContextName); this.clientSSLContext = (SSLContext) container.getRequiredService(clientContextServiceName).getValue(); } @Override public ServerSocket createServerSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { if (type.equals(Constants.SSL_SOCKET_TYPE)) { return createSSLServerSocket(inetSocketAddress.getPort(), 1000, InetAddress.getByName(inetSocketAddress.getHostName())); } else { return super.createServerSocket(type, inetSocketAddress); } } @Override public Socket createSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { if (type.contains(Constants.SSL_SOCKET_TYPE)){ return createSSLSocket(inetSocketAddress.getHostName(), inetSocketAddress.getPort()); } else { return super.createSocket(type, inetSocketAddress); } } public Socket createSSLSocket(String host, int port) throws IOException { InetAddress address = InetAddress.getByName(host); javax.net.ssl.SSLSocketFactory socketFactory = this.clientSSLContext.getSocketFactory(); return socketFactory.createSocket(address, port); } public ServerSocket createSSLServerSocket(int port, int backlog, InetAddress inetAddress) throws IOException { SSLServerSocketFactory serverSocketFactory = this.serverSSLContext.getServerSocketFactory(); return serverSocketFactory.createServerSocket(port, backlog, inetAddress); } private ServiceContainer currentServiceContainer() { if(WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION); } return CurrentServiceContainer.getServiceContainer(); } }
4,694
39.826087
131
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/security/NoSSLSocketFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.security; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * <p> * This class is responsible for creating Sockets used by IIOP subsystem. * <p> * * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class NoSSLSocketFactory extends SocketFactoryBase { @Override public ServerSocket createServerSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { //we can only warn here because of backward compatibility if (type.equals(Constants.SSL_SOCKET_TYPE)) { IIOPLogger.ROOT_LOGGER.cannotCreateSSLSocket(); } return super.createServerSocket(type, inetSocketAddress); } @Override public Socket createSocket(String type, InetSocketAddress inetSocketAddress) throws IOException { //we can only warn here because of backward compatibility if (type.contains(Constants.SSL_SOCKET_TYPE)){ IIOPLogger.ROOT_LOGGER.cannotCreateSSLSocket(); } return super.createSocket(type, inetSocketAddress); } }
2,280
34.640625
113
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/CorbaServiceUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import org.jboss.as.naming.ServiceBasedNamingStore; import org.jboss.as.naming.ValueManagedReferenceFactory; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.naming.service.BinderService; import org.jboss.msc.service.ServiceTarget; /** * <p> * Utility class used by the CORBA related services. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class CorbaServiceUtil { /** * <p> * Private constructor as required by the {@code Singleton} pattern. * </p> */ private CorbaServiceUtil() { } /** * <p> * Adds a {@code BinderService} to the specified target. The service binds the specified value to JNDI under the * {@code java:/jboss/contextName} context. * </p> * * @param target the {@code ServiceTarget} where the service will be added. * @param contextName the JNDI context name where the value will be bound. * @param value the value to be bound. */ public static void bindObject(final ServiceTarget target, final String contextName, final Object value) { final BinderService binderService = new BinderService(contextName); binderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(value)); target.addService(ContextNames.buildServiceName(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, contextName), binderService) .addDependency(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()) .install(); } }
2,667
39.424242
142
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/SecurityActions.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import static java.security.AccessController.doPrivileged; import org.wildfly.security.manager.WildFlySecurityManager; import org.wildfly.security.manager.action.CreateThreadAction; /** * <p> * This class defines actions that must be executed in privileged blocks. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ class SecurityActions { /** * <p> * Creates a thread with the specified {@code Runnable} and name. * </p> * * @param runnable the {@code Runnable} to be set in the new {@code Thread}. * @param threadName the name of the new {@code Thread}. * @return the construct {@code Thread} instance. */ static Thread createThread(final Runnable runnable, final String threadName) { return ! WildFlySecurityManager.isChecking() ? new Thread(runnable, threadName) : doPrivileged(new CreateThreadAction(runnable, threadName)); } }
1,998
37.442308
149
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/CorbaNamingService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import java.nio.charset.StandardCharsets; import java.util.Properties; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.omg.CORBA.ORB; import org.omg.CosNaming.NamingContextExt; import org.omg.CosNaming.NamingContextExtHelper; import org.omg.PortableServer.POA; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.IIOPExtension; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.naming.CorbaNamingContext; /** * <p> * This class implements a {@code Service} that provides the default CORBA naming service for JBoss to use. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class CorbaNamingService implements Service<NamingContextExt> { public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append(IIOPExtension.SUBSYSTEM_NAME, "naming-service"); private static final Properties properties = new Properties(); private final InjectedValue<POA> rootPOAInjector = new InjectedValue<POA>(); private final InjectedValue<POA> namingPOAInjector = new InjectedValue<POA>(); private final InjectedValue<ORB> orbInjector = new InjectedValue<ORB>(); private volatile NamingContextExt namingService; public CorbaNamingService(Properties props) { if (props != null) { properties.putAll(props); } } @Override public void start(StartContext context) throws StartException { IIOPLogger.ROOT_LOGGER.debugf("Starting service %s", context.getController().getName().getCanonicalName()); ORB orb = orbInjector.getValue(); POA rootPOA = rootPOAInjector.getValue(); POA namingPOA = namingPOAInjector.getValue(); try { // initialize the static naming service variables. CorbaNamingContext.init(orb, rootPOA); // create and initialize the root context instance according to the configuration. CorbaNamingContext ns = new CorbaNamingContext(); ns.init(namingPOA, false, false); // create and activate the root context. byte[] rootContextId = "root".getBytes(StandardCharsets.UTF_8); namingPOA.activate_object_with_id(rootContextId, ns); namingService = NamingContextExtHelper.narrow(namingPOA.create_reference_with_id(rootContextId, "IDL:omg.org/CosNaming/NamingContextExt:1.0")); // exporting the NameService initial reference ((com.sun.corba.se.impl.orb.ORBImpl) orb).register_initial_reference(Constants.NAME_SERVICE_INIT_REF, namingPOA.servant_to_reference(ns)); // exporting root-context initial reference final boolean exportCorbaloc = properties.getProperty(Constants.NAMING_EXPORT_CORBALOC).equals("true"); if (exportCorbaloc) { final String rootContext = properties.getProperty(Constants.NAMING_ROOT_CONTEXT); ((com.sun.corba.se.impl.orb.ORBImpl) orb).register_initial_reference(rootContext, namingPOA.servant_to_reference(ns)); } } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.failedToStartJBossCOSNaming(e); } // bind the corba naming service to JNDI. CorbaServiceUtil.bindObject(context.getChildTarget(), "corbanaming", namingService); if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.corbaNamingServiceStarted(); IIOPLogger.ROOT_LOGGER.debugf("Naming: [%s]", orb.object_to_string(namingService)); } } @Override public void stop(StopContext context) { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Stopping service %s", context.getController().getName().getCanonicalName()); } } @Override public NamingContextExt getValue() throws IllegalStateException, IllegalArgumentException { return this.namingService; } /** * <p> * Obtains a reference to the {@code ORB} injector which allows the injection of the running {@code ORB} that will * be used to initialize the naming service. * </p> * * @return the {@code Injector<ORB>} used to inject the running {@code ORB}. */ public Injector<ORB> getORBInjector() { return this.orbInjector; } /** * <p> * Obtains a reference to the {@code RootPOA} injector which allows the injection of the root {@code POA} that will * be used to initialize the naming service. * </p> * * @return the {@code Injector<POA>} used to inject the root {@code POA}. */ public Injector<POA> getRootPOAInjector() { return this.rootPOAInjector; } /** * <p> * Obtains a reference to the {@code POA} injector which allows the injection of the {@code POA} that will be used * activate the naming service. * </p> * * @return the {@code Injector<POA>} used to inject the naming service {@code POA}. */ public Injector<POA> getNamingPOAInjector() { return this.namingPOAInjector; } }
6,554
38.251497
124
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/CorbaPOAService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import java.util.ArrayList; import java.util.List; import com.sun.corba.se.spi.extension.ZeroPortPolicy; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.omg.CORBA.ORB; import org.omg.CORBA.Policy; import org.omg.PortableServer.IdAssignmentPolicyValue; import org.omg.PortableServer.IdUniquenessPolicyValue; import org.omg.PortableServer.ImplicitActivationPolicyValue; import org.omg.PortableServer.LifespanPolicyValue; import org.omg.PortableServer.POA; import org.omg.PortableServer.POAHelper; import org.omg.PortableServer.RequestProcessingPolicyValue; import org.omg.PortableServer.ServantRetentionPolicyValue; import org.omg.PortableServer.ThreadPolicyValue; import org.wildfly.iiop.openjdk.IIOPExtension; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * <p> * This class implements a service that creates and activates {@code org.omg.PortableServer.POA} objects. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class CorbaPOAService implements Service<POA> { public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append(IIOPExtension.SUBSYSTEM_NAME, "poa-service"); public static final ServiceName ROOT_SERVICE_NAME = SERVICE_NAME.append("rootpoa"); public static final ServiceName INTERFACE_REPOSITORY_SERVICE_NAME = SERVICE_NAME.append("irpoa"); private volatile POA poa; private final InjectedValue<ORB> orbInjector = new InjectedValue<ORB>(); private final InjectedValue<POA> parentPOAInjector = new InjectedValue<POA>(); private final String poaName; private final String bindingName; // the policy values that can be assigned to created POAs. private final IdAssignmentPolicyValue idAssignmentPolicyValue; private final IdUniquenessPolicyValue idUniquenessPolicyValue; private final ImplicitActivationPolicyValue implicitActivationPolicyValue; private final LifespanPolicyValue lifespanPolicyValue; private final RequestProcessingPolicyValue requestProcessingPolicyValue; private final ServantRetentionPolicyValue servantRetentionPolicyValue; private final ThreadPolicyValue threadPolicyValue; private final boolean sslOnly; /** * <p> * Creates a {@code CorbaPOAService} with the specified POA name and binding name. The {@code POA} created by this * service will not be associated with any policies. * </p> * * @param poaName the name of the {@code POA} that will be created by this service (ex. "RootPOA"). * @param bindingName the JNDI context name where the created {@code POA} will be bound. If null, the JNDI binding * won't be performed. */ public CorbaPOAService(String poaName, String bindingName, boolean sslOnly) { this(poaName, bindingName, sslOnly, null, null, null, null, null, null, null); } /** * <p> * Creates a {@code CorbaPOAService} with the specified POA name, binding name and policy values. * </p> * * @param poaName the name of the {@code POA} that will be created by this service (ex. "RootPOA"). * @param bindingName the JNDI context name where the created {@code POA} will be bound. If null, the JNDI binding * won't be performed. * @param idAssignmentPolicyValue the {@code IdAssignmentPolicyValue} that will be associated with the created * {@code POA}. Can be null. * @param idUniquenessPolicyValue the {@code IdUniquenessPolicyValue} that will be associated with the created * {@code POA}. Can be null. * @param implicitActivationPolicyValue the {@code ImplicitActivationPolicyValue} that will be associated with the * created {@code POA}. Can be null. * @param lifespanPolicyValue the {@code LifespanPolicyValue} that will be associated with the created {@code POA}. * Can be null. * @param requestProcessingPolicyValue the {@code RequestProcessingPolicyValue} that will be associated with the * created {@code POA}. Can be null. * @param servantRetentionPolicyValue the {@code ServantRetentionPolicyValue} that will be associated with the created * {@code POA}. Can be null. * @param threadPolicyValue the {@code ThreadPolicyValue} that will be associated with the created {@code POA}. Can * be null. */ public CorbaPOAService(String poaName, String bindingName, boolean sslOnly, IdAssignmentPolicyValue idAssignmentPolicyValue, IdUniquenessPolicyValue idUniquenessPolicyValue, ImplicitActivationPolicyValue implicitActivationPolicyValue, LifespanPolicyValue lifespanPolicyValue, RequestProcessingPolicyValue requestProcessingPolicyValue, ServantRetentionPolicyValue servantRetentionPolicyValue, ThreadPolicyValue threadPolicyValue) { this.poaName = poaName; this.bindingName = bindingName; this.sslOnly = sslOnly; this.idAssignmentPolicyValue = idAssignmentPolicyValue; this.idUniquenessPolicyValue = idUniquenessPolicyValue; this.implicitActivationPolicyValue = implicitActivationPolicyValue; this.lifespanPolicyValue = lifespanPolicyValue; this.requestProcessingPolicyValue = requestProcessingPolicyValue; this.servantRetentionPolicyValue = servantRetentionPolicyValue; this.threadPolicyValue = threadPolicyValue; } @Override public void start(StartContext context) throws StartException { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Starting service %s", context.getController().getName().getCanonicalName()); } ORB orb = this.orbInjector.getOptionalValue(); POA parentPOA = this.parentPOAInjector.getOptionalValue(); // if an ORB has been injected, we will use the ORB.resolve_initial_references method to instantiate the POA. if (orb != null) { try { this.poa = POAHelper.narrow(orb.resolve_initial_references(this.poaName)); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.errorResolvingInitRef(this.poaName, e); } } // if a parent POA has been injected, we use it to create the policies and then the POA itself. else if (parentPOA != null) { try { Policy[] poaPolicies = this.createPolicies(parentPOA); this.poa = parentPOA.create_POA(this.poaName, null, poaPolicies); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.errorCreatingPOAFromParent(e); } } else { throw IIOPLogger.ROOT_LOGGER.invalidPOACreationArgs(); } // check if the POA should be bound to JNDI under java:/jboss. if (this.bindingName != null) { CorbaServiceUtil.bindObject(context.getChildTarget(), this.bindingName, this.poa); } // activate the created POA. try { this.poa.the_POAManager().activate(); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.errorActivatingPOA(e); } } @Override public void stop(StopContext context) { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Stopping service %s", context.getController().getName().getCanonicalName()); } // destroy parent POAs, letting they destroy their children POAs in the process. if (this.poa.the_parent() == null) this.poa.destroy(false, true); } @Override public POA getValue() throws IllegalStateException, IllegalArgumentException { return this.poa; } public Injector<ORB> getORBInjector() { return this.orbInjector; } public Injector<POA> getParentPOAInjector() { return this.parentPOAInjector; } /** * <p> * Create the {@code Policy} array containing the {@code POA} policies using the values specified in the constructor. * When creating a {@code POA}, the parent {@code POA} is responsible for generating the relevant policies beforehand. * </p> * * @param poa the {@code POA} used to create the {@code Policy} objects. * @return the constructed {@code Policy} array. */ private Policy[] createPolicies(POA poa) { List<Policy> policies = new ArrayList<Policy>(); if(this.sslOnly) policies.add(ZeroPortPolicy.getPolicy()); if (this.idAssignmentPolicyValue != null) policies.add(poa.create_id_assignment_policy(this.idAssignmentPolicyValue)); if (this.idUniquenessPolicyValue != null) policies.add(poa.create_id_uniqueness_policy(this.idUniquenessPolicyValue)); if (this.implicitActivationPolicyValue != null) policies.add(poa.create_implicit_activation_policy(this.implicitActivationPolicyValue)); if (this.lifespanPolicyValue != null) policies.add(poa.create_lifespan_policy(this.lifespanPolicyValue)); if (this.requestProcessingPolicyValue != null) policies.add(poa.create_request_processing_policy(this.requestProcessingPolicyValue)); if (this.servantRetentionPolicyValue != null) policies.add(poa.create_servant_retention_policy(this.servantRetentionPolicyValue)); if (this.threadPolicyValue != null) policies.add(poa.create_thread_policy(this.threadPolicyValue)); return policies.toArray(new Policy[policies.size()]); } }
11,299
44.934959
136
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/IORSecConfigMetaDataService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import java.security.AccessController; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.iiop.openjdk.IIOPExtension; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * <p> * Service that holds the configured {@code IORSecurityConfigMetaData}. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class IORSecConfigMetaDataService implements Service<IORSecurityConfigMetaData> { public static final ServiceName SERVICE_NAME = ServiceName.JBOSS .append(IIOPExtension.SUBSYSTEM_NAME, "ior-security-config"); private IORSecurityConfigMetaData iorSecurityConfigMetaData; public IORSecConfigMetaDataService(final IORSecurityConfigMetaData metaData) { this.iorSecurityConfigMetaData = metaData; } @Override public void start(final StartContext startContext) throws StartException { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Starting service %s", startContext.getController().getName().getCanonicalName()); } } @Override public void stop(final StopContext stopContext) { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Stopping service %s", stopContext.getController().getName().getCanonicalName()); } } @Override public IORSecurityConfigMetaData getValue() throws IllegalStateException, IllegalArgumentException { return this.iorSecurityConfigMetaData; } public static IORSecurityConfigMetaData getCurrent() { return (IORSecurityConfigMetaData) currentServiceContainer().getRequiredService(SERVICE_NAME).getValue(); } private static ServiceContainer currentServiceContainer() { if (System.getSecurityManager() == null) { return CurrentServiceContainer.getServiceContainer(); } return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION); } }
3,373
38.232558
124
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/service/CorbaORBService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.service; import java.net.InetSocketAddress; import java.security.AccessController; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.network.ManagedBinding; import org.jboss.as.network.SocketBinding; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.omg.CORBA.ORB; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.IIOPExtension; import org.wildfly.iiop.openjdk.csiv2.CSIV2IORToSocketInfo; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.naming.jndi.CorbaUtils; import org.wildfly.security.manager.WildFlySecurityManager; import com.sun.corba.se.impl.orb.ORBImpl; import com.sun.corba.se.impl.orb.ORBSingleton; import com.sun.corba.se.impl.orbutil.ORBConstants; /** * <p> * This class implements a {@code Service} that creates and installs a CORBA {@code ORB}. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class CorbaORBService implements Service<ORB> { public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append(IIOPExtension.SUBSYSTEM_NAME, "orb-service"); private static final Properties properties = new Properties(); private final Consumer<ORB> serviceConsumer; private final Supplier<ExecutorService> executorServiceSupplier; private final Supplier<SocketBinding> iiopSocketBindingSupplier; private final Supplier<SocketBinding> iiopSSLSocketBindingSupplier; private volatile ORB orb; /** * <p> * Creates an instance of {@code CorbaORBService} with the specified {@code ORBImplementation} and initializers. * </p> * * @param props a {@code Properties} instance containing the IIOP subsystem configuration properties. */ public CorbaORBService(Properties props, final Consumer<ORB> serviceConsumer, final Supplier<ExecutorService> executorServiceSupplier, final Supplier<SocketBinding> iiopSocketBindingSupplier, final Supplier<SocketBinding> iiopSSLSocketBindingSupplier) { if (props != null) { properties.putAll(props); } this.serviceConsumer = serviceConsumer; this.executorServiceSupplier = executorServiceSupplier; this.iiopSocketBindingSupplier = iiopSocketBindingSupplier; this.iiopSSLSocketBindingSupplier = iiopSSLSocketBindingSupplier; } @Override public void start(StartContext context) throws StartException { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Starting service %s", context.getController().getName().getCanonicalName()); } try { // set the ORBClass and ORBSingleton class as system properties. properties.setProperty(Constants.ORB_CLASS, ORBImpl.class.getName()); properties.setProperty(Constants.ORB_SINGLETON_CLASS, ORBSingleton.class.getName()); WildFlySecurityManager.setPropertyPrivileged(Constants.ORB_CLASS, ORBImpl.class.getName()); WildFlySecurityManager.setPropertyPrivileged(Constants.ORB_SINGLETON_CLASS, ORBSingleton.class.getName()); properties.setProperty(ORBConstants.IOR_TO_SOCKET_INFO_CLASS_PROPERTY, CSIV2IORToSocketInfo.class.getName()); // set the IIOP and IIOP/SSL ports from the respective socket bindings. final SocketBinding socketBinding = iiopSocketBindingSupplier.get(); final SocketBinding sslSocketBinding = iiopSSLSocketBindingSupplier.get(); if (socketBinding != null) { InetSocketAddress address = this.iiopSocketBindingSupplier.get().getSocketAddress(); properties.setProperty(ORBConstants.SERVER_HOST_PROPERTY, address.getAddress().getHostAddress()); properties.setProperty(ORBConstants.SERVER_PORT_PROPERTY, String.valueOf(address.getPort())); properties.setProperty(ORBConstants.PERSISTENT_SERVER_PORT_PROPERTY, String.valueOf(address.getPort())); socketBinding.getSocketBindings().getNamedRegistry().registerBinding(ManagedBinding.Factory.createSimpleManagedBinding(socketBinding)); } if (sslSocketBinding != null) { InetSocketAddress address = this.iiopSSLSocketBindingSupplier.get().getSocketAddress(); properties.setProperty(ORBConstants.SERVER_HOST_PROPERTY, address.getAddress().getHostAddress()); properties.setProperty(Constants.ORB_SSL_PORT, String.valueOf(address.getPort())); final String sslSocket = new StringBuilder().append(Constants.SSL_SOCKET_TYPE).append(':') .append(String.valueOf(address.getPort())).toString(); properties.setProperty(ORBConstants.LISTEN_SOCKET_PROPERTY, sslSocket); if (!properties.containsKey(Constants.ORB_ADDRESS)) { properties.setProperty(Constants.ORB_ADDRESS, address.getAddress().getHostAddress()); } sslSocketBinding.getSocketBindings().getNamedRegistry().registerBinding(ManagedBinding.Factory.createSimpleManagedBinding(sslSocketBinding)); } // initialize the ORB - the thread context classloader needs to be adjusted as the ORB classes are loaded via reflection. ClassLoader loader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(WildFlySecurityManager.getClassLoaderPrivileged(this.getClass())); this.orb = ORB.init(new String[0], properties); // initialize the ORBSingleton. ORB.init(); } finally { // restore the thread context classloader. WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(loader); } // start the ORB in a separate thread. Thread orbThread = SecurityActions.createThread(new ORBRunner(this.orb), "ORB Run Thread"); orbThread.start(); // bind the ORB to JNDI under java:/jboss/ORB. ServiceTarget target = context.getChildTarget(); CorbaServiceUtil.bindObject(target, "ORB", this.orb); } catch (Exception e) { throw new StartException(e); } serviceConsumer.accept(this.orb); CorbaUtils.setOrbProperties(properties); IIOPLogger.ROOT_LOGGER.corbaORBServiceStarted(); } @Override public void stop(StopContext context) { if (IIOPLogger.ROOT_LOGGER.isDebugEnabled()) { IIOPLogger.ROOT_LOGGER.debugf("Stopping service %s", context.getController().getName().getCanonicalName()); } final SocketBinding socketBinding = iiopSocketBindingSupplier.get(); final SocketBinding sslSocketBinding = iiopSSLSocketBindingSupplier.get(); if (socketBinding != null) { socketBinding.getSocketBindings().getNamedRegistry().unregisterBinding(socketBinding.getName()); } if (sslSocketBinding != null) { sslSocketBinding.getSocketBindings().getNamedRegistry().unregisterBinding(sslSocketBinding.getName()); } // stop the ORB asynchronously. final ORBDestroyer destroyer = new ORBDestroyer(this.orb, context); try { executorServiceSupplier.get().execute(destroyer); } catch (RejectedExecutionException e) { destroyer.run(); } finally { context.asynchronous(); } serviceConsumer.accept(null); } @Override public ORB getValue() throws IllegalStateException, IllegalArgumentException { return this.orb; } /** * <p> * Gets the value of the specified ORB property. All ORB properties can be queried using this method. This includes * the properties that have been explicitly set by this service prior to creating the ORB and all IIOP properties * that have been specified in the IIOP subsystem configuration. * </p> * * @param key the property key. * @return the property value or {@code null} if the property with the specified key hasn't been configured. */ public static String getORBProperty(String key) { return properties.getProperty(key); } public static ORB getCurrent() { return (ORB) currentServiceContainer().getRequiredService(SERVICE_NAME).getValue(); } /** * <p> * The {@code ORBRunner} calls the blocking {@code run()} method on the specified {@code ORB} instance and is used * to start the {@code ORB} in a dedicated thread. * </p> */ private class ORBRunner implements Runnable { private ORB orb; public ORBRunner(ORB orb) { this.orb = orb; } @Override public void run() { this.orb.run(); } } /** * <p> * The {@code ORBDestroyer} is responsible for destroying the specified {@code ORB} instance without blocking the * thread that called {@code stop} on {@code CorbaORBService}. * </p> */ private class ORBDestroyer implements Runnable { private ORB orb; private StopContext context; public ORBDestroyer(ORB orb, StopContext context) { this.orb = orb; this.context = context; } @Override public void run() { // orb.destroy blocks until the ORB has shutdown. We must signal the context when the process is complete. try { CorbaUtils.setOrbProperties(null); this.orb.destroy(); } finally { this.context.complete(); } } } private static ServiceContainer currentServiceContainer() { if(System.getSecurityManager() == null) { return CurrentServiceContainer.getServiceContainer(); } return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION); } }
11,610
42.003704
257
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/logging/IIOPLogger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.logging; import org.jboss.as.controller.OperationFailedException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Param; import org.jboss.msc.service.StartException; import org.omg.CORBA.BAD_INV_ORDER; import org.omg.CORBA.CompletionStatus; import org.omg.CORBA.INTERNAL; import org.omg.CORBA.MARSHAL; import org.omg.CORBA.NO_PERMISSION; import org.wildfly.iiop.openjdk.rmi.RMIIIOPViolationException; import org.wildfly.iiop.openjdk.rmi.ir.IRConstructionException; import javax.naming.ConfigurationException; import javax.naming.InvalidNameException; import javax.naming.NamingException; import java.io.IOException; import java.net.MalformedURLException; import static org.jboss.logging.Logger.Level.*; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ @MessageLogger(projectCode = "WFLYIIOP", length = 4) public interface IIOPLogger extends BasicLogger { IIOPLogger ROOT_LOGGER = Logger.getMessageLogger(IIOPLogger.class, "org.wildfly.iiop.openjdk"); @LogMessage(level = INFO) @Message(id = 1, value = "Activating IIOP Subsystem") void activatingSubsystem(); @LogMessage(level = ERROR) @Message(id = 2, value = "Error fetching CSIv2Policy") void failedToFetchCSIv2Policy(@Cause Throwable cause); @LogMessage(level = WARN) @Message(id = 3, value = "Caught exception while encoding GSSUPMechOID") void caughtExceptionEncodingGSSUPMechOID(@Cause Throwable cause); @LogMessage(level = ERROR) @Message(id = 4, value = "Internal error") void logInternalError(@Cause Exception cause); @LogMessage(level = ERROR) @Message(id = 5, value = "Failed to create CORBA naming context") void failedToCreateNamingContext(@Cause Exception cause); @LogMessage(level = WARN) @Message(id = 6, value = "Unbind failed for %s") void failedToUnbindObject(Object name); @LogMessage(level = ERROR) @Message(id = 7, value = "Failed to obtain JSSE security domain with name %s") void failedToObtainJSSEDomain(String securityDomain); @LogMessage(level = INFO) @Message(id = 8, value = "CORBA Naming Service started") void corbaNamingServiceStarted(); @LogMessage(level = INFO) @Message(id = 9, value = "CORBA ORB Service started") void corbaORBServiceStarted(); @LogMessage(level = WARN) @Message(id = 10, value = "Compatibility problem: Class javax.rmi.CORBA.ClassDesc does not conform to the Java(TM) Language to IDL Mapping Specification (01-06-07), section 1.3.5.11") void warnClassDescDoesNotConformToSpec(); @LogMessage(level = WARN) @Message(id = 11, value = "Could not deactivate IR object") void warnCouldNotDeactivateIRObject(@Cause Throwable cause); @LogMessage(level = WARN) @Message(id = 12, value = "Could not deactivate anonymous IR object") void warnCouldNotDeactivateAnonIRObject(@Cause Throwable cause); @Message(id = 13, value = "SSL support has been enabled but no security domain or client/server SSL contexts have been specified") OperationFailedException noSecurityDomainOrSSLContextsSpecified(); @Message(id = 14, value = "Unexpected exception") RuntimeException unexpectedException(@Cause Throwable cause); @Message(id = 15, value = "Unexpected ContextError in SAS reply") NO_PERMISSION unexpectedContextErrorInSASReply(@Param int minorCode, @Param CompletionStatus status); @Message(id = 16, value = "Could not parse SAS reply: %s") MARSHAL errorParsingSASReply(Exception e, @Param int minorCode, @Param CompletionStatus status); @Message(id = 17, value = "Could not register initial reference for SASCurrent") RuntimeException errorRegisteringSASCurrentInitRef(@Cause Throwable cause); @Message(id = 18, value = "SAS context does not exist") NO_PERMISSION missingSASContext(); @Message(id = 19, value = "Could not decode initial context token") NO_PERMISSION errorDecodingInitContextToken(); @Message(id = 20, value = "Could not decode target name in initial context token") NO_PERMISSION errorDecodingTargetInContextToken(); @Message(id = 21, value = "Could not decode incoming principal name") NO_PERMISSION errorDecodingPrincipalName(); @Message(id = 22, value = "Exception decoding context data in %s") RuntimeException errorDecodingContextData(String interceptorName, @Cause Throwable e); @Message(id = 23, value = "Batch size not numeric: %s") IllegalArgumentException illegalBatchSize(String batch); @Message(id = 24, value = "Error getting binding list") NamingException errorGettingBindingList(); @Message(id = 25, value = "Error generating object via object factory") NamingException errorGeneratingObjectViaFactory(); @Message(id = 26, value = "Error constructing context: either ORB or NamingContext must be supplied") ConfigurationException errorConstructingCNCtx(); @Message(id = 27, value = "%s does not name a NamingContext") ConfigurationException notANamingContext(String name); @Message(id = 28, value = "Cannot convert IOR to NamingContext: %s") ConfigurationException errorConvertingIORToNamingCtx(String ior); @Message(id = 29, value = "ORB.resolve_initial_references(\"NameService\") does not return a NamingContext") ConfigurationException errorResolvingNSInitRef(); @Message(id = 30, value = "COS Name Service not registered with ORB under the name 'NameService'") NamingException cosNamingNotRegisteredCorrectly(); @Message(id = 31, value = "Cannot connect to ORB") NamingException errorConnectingToORB(); @Message(id = 32, value = "Invalid IOR or URL: %s") NamingException invalidURLOrIOR(String ior); @Message(id = 33, value = "Invalid object reference: %s") NamingException invalidObjectReference(String ior); @Message(id = 34, value = "%s does not contain an IOR") ConfigurationException urlDoesNotContainIOR(String url); @Message(id = 35, value = "Only instances of org.omg.CORBA.Object can be bound") IllegalArgumentException notACorbaObject(); @Message(id = 36, value = "No object reference bound for specified name") NamingException noReferenceFound(); @Message(id = 37, value = "Invalid empty name") InvalidNameException invalidEmptyName(); @Message(id = 38, value = "%s: unescaped \\ at end of component") InvalidNameException unescapedCharacter(String cnString); @Message(id = 39, value = "%s: Invalid character being escaped") InvalidNameException invalidEscapedCharacter(String cnString); @Message(id = 40, value = "Invalid %s URL: %s") MalformedURLException invalidURL(String protocol, String url); @Message(id = 41, value = "Problem with PortableRemoteObject.toStub(); object not exported or stub not found") ConfigurationException problemInvokingPortableRemoteObjectToStub(); @Message(id = 42, value = "Cannot invoke javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote)") ConfigurationException cannotInvokePortableRemoteObjectToStub(); @Message(id = 43, value = "No method definition for javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote)") IllegalStateException noMethodDefForPortableRemoteObjectToStub(); @Message(id = 44, value = "Problem invoking javax.rmi.CORBA.Stub.connect()") ConfigurationException problemInvokingStubConnect(); @Message(id = 45, value = "Cannot invoke javax.rmi.CORBA.Stub.connect()") ConfigurationException cannotInvokeStubConnect(); @Message(id = 46, value = "No method definition for javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB)") IllegalStateException noMethodDefForStubConnect(); @Message(id = 47, value = "Invalid IIOP URL version: %s") MalformedURLException invalidIIOPURLVersion(String version); @Message(id = 48, value = "javax.rmi packages not available") ConfigurationException unavailableRMIPackages(); @Message(id = 49, value = "ISO-Latin-1 decoder unavailable") MalformedURLException unavailableISOLatin1Decoder(); @Message(id = 50, value = "Invalid URI encoding: %s") MalformedURLException invalidURIEncoding(String encoding); @Message(id = 51, value = "Error configuring domain socket factory: failed to lookup JSSE security domain") ConfigurationException failedToLookupJSSEDomain(); @Message(id = 52, value = "keyManager[] is null for security domain %s") IOException errorObtainingKeyManagers(String securityDomain); @Message(id = 53, value = "Failed to get SSL context") IOException failedToGetSSLContext(@Cause Throwable cause); @Message(id = 54, value = "Failed to start the JBoss Corba Naming Service") StartException failedToStartJBossCOSNaming(@Cause Throwable cause); @Message(id = 55, value = "Foreign Transaction") UnsupportedOperationException foreignTransaction(); @Message(id = 56, value = "Exception raised during encoding") RuntimeException errorEncodingContext(@Cause Throwable cause); @Message(id = 57, value = "Exception getting slot in TxServerInterceptor") RuntimeException errorGettingSlotInTxInterceptor(@Cause Throwable cause); @Message(id = 58, value = "Exception setting slot in TxServerInterceptor") RuntimeException errorSettingSlotInTxInterceptor(@Cause Throwable cause); @Message(id = 59, value = "Cannot analyze a null class") IllegalArgumentException cannotAnalyzeNullClass(); @Message(id = 60, value = "Bad type for a constant: %s") IllegalArgumentException badConstantType(String type); @Message(id = 61, value = "Cannot analyze special class: %s") IllegalArgumentException cannotAnalyzeSpecialClass(String type); @Message(id = 62, value = "Not an accessor: %s") IllegalArgumentException notAnAccessor(String name); @Message(id = 63, value = "Not a class or interface: %s") IllegalArgumentException notAnClassOrInterface(String name); @Message(id = 64, value = "Class %s is not an interface") IllegalArgumentException notAnInterface(String name); @Message(id = 65, value = "Not a primitive type: %s") IllegalArgumentException notAPrimitive(String type); @Message(id = 66, value = "Field %s of interface %s is a constant, but it is not primitive or String") RMIIIOPViolationException badRMIIIOPConstantType(String field, String intface, @Param String section); @Message(id = 67, value = "Exception type %s must be a checked exception class") RMIIIOPViolationException badRMIIIOPExceptionType(String type, @Param String section); @Message(id = 68, value = "All interface methods must throw javax.rmi.RemoteException but method %s of interface %s does not") RMIIIOPViolationException badRMIIIOPMethodSignature(String method, String intface, @Param String section); @Message(id = 69, value = "Name cannot be null, empty or qualified") IllegalArgumentException nameCannotBeNullEmptyOrQualified(); @Message(id = 70, value = "Primitive types have no IR IDs") IllegalArgumentException primitivesHaveNoIRIds(); @Message(id = 71, value = "No SHA message digest available") RuntimeException unavailableSHADigest(@Cause Throwable cause); @Message(id = 72, value = "Unknown primitive type: %s") RuntimeException unknownPrimitiveType(String type); @Message(id = 73, value = "Cannot analyze java.lang.String: it is a special case") IllegalArgumentException cannotAnalyzeStringType(); @Message(id = 74, value = "Cannot analyze java.lang.Class: it is a special case") IllegalArgumentException cannotAnalyzeClassType(); @Message(id = 75, value = "Value type %s cannot implement java.rmi.Remote") RMIIIOPViolationException valueTypeCantImplementRemote(String type, @Param String section); @Message(id = 76, value = "Value type %s cannot be a proxy or inner class") RMIIIOPViolationException valueTypeCantBeProxy(String type); @Message(id = 77, value = "Error loading class %s") RuntimeException errorLoadingClass(String type, @Cause Throwable cause); @Message(id = 78, value = "No read method in helper class %s") RuntimeException noReadMethodInHelper(String type, @Cause Throwable cause); @Message(id = 79, value = "No write method in helper class %s") RuntimeException noWriteMethodInHelper(String type, @Cause Throwable cause); @Message(id = 80, value = "Error unmarshaling %s") RuntimeException errorUnmarshaling(Class<?> type, @Cause Throwable cause); @Message(id = 81, value = "Error marshaling %s") RuntimeException errorMarshaling(Class<?> type, @Cause Throwable cause); @Message(id = 82, value = "Cannot obtain exception repository id for %s") RuntimeException cannotObtainExceptionRepositoryID(String type, @Cause Throwable cause); @Message(id = 83, value = "Cannot marshal parameter: unexpected number of parameters") RuntimeException errorMashalingParams(); @Message(id = 84, value = "Cannot change RMI/IIOP mapping") BAD_INV_ORDER cannotChangeRMIIIOPMapping(); @Message(id = 85, value = "Bad kind %d for TypeCode") RuntimeException badKindForTypeCode(int kind); @Message(id = 86, value = "Wrong interface repository") IRConstructionException wrongInterfaceRepository(); @Message(id = 87, value = "Duplicate repository name") IRConstructionException duplicateRepositoryName(); @Message(id = 88, value = "Invalid null class") IllegalArgumentException invalidNullClass(); @Message(id = 89, value = "Bad class %s for a constant") IRConstructionException badClassForConstant(String className); @Message(id = 90, value = "TypeCode for class %s is unknown") IRConstructionException unknownTypeCodeForClass(String className); @Message(id = 91, value = "TypeCode for class %s already established") IRConstructionException duplicateTypeCodeForClass(String className); @Message(id = 92, value = "Name collision while creating package") IRConstructionException collisionWhileCreatingPackage(); @Message(id = 93, value = "Class %s is not an array class") IRConstructionException classIsNotArray(String className); @Message(id = 94, value = "Cannot destroy RMI/IIOP mapping") BAD_INV_ORDER cannotDestroyRMIIIOPMapping(); @Message(id = 95, value = "Bad kind for super valuetype of %s") IRConstructionException badKindForSuperValueType(String id); @Message(id = 96, value = "ValueDef %s unable to resolve reference to implemented interface %s") IRConstructionException errorResolvingRefToImplementedInterface(String id, String intface); @Message(id = 97, value = "ValueDef %s unable to resolve reference to abstract base valuetype %s") IRConstructionException errorResolvingRefToAbstractValuetype(String id, String valuetype); @Message(id = 98, value = "Failed to resolve initial reference %s") StartException errorResolvingInitRef(String refName, @Cause Throwable cause); @Message(id = 99, value = "Failed to create POA from parent") StartException errorCreatingPOAFromParent(@Cause Throwable cause); @Message(id = 100, value = "Unable to instantiate POA: either the running ORB or the parent POA must be specified") StartException invalidPOACreationArgs(); @Message(id = 101, value = "Failed to activate POA") StartException errorActivatingPOA(@Cause Throwable cause); @Message(id = 102, value = "Caught exception destroying Iterator %s") INTERNAL exceptionDestroingIterator(String cause); @Message(id = 103, value = "IOR settings imply ssl connections usage, but secure connections have not been configured") OperationFailedException sslNotConfigured(); @Message(id = 104, value = "Inconsistent transport-config configuration: %s is supported, please configure it to %s value") String inconsistentSupportedTransportConfig(final String transportAttributeName, final String suggested); @Message(id = 105, value = "Inconsistent transport-config configuration: %s is not supported, please remove it or configure it to none value") String inconsistentUnsupportedTransportConfig(final String transportAttributeName); @Message(id = 106, value = "Inconsistent transport-config configuration: %s is set to true, please configure %s as required") String inconsistentRequiredTransportConfig(final String requiredAttributeName, final String transportAttributeName); // @Message(id = 108, value = "Security attribute server-requires-ssl is not supported in previous iiop-openjdk versions and can't be converted") // String serverRequiresSslNotSupportedInPreviousVersions(); @LogMessage(level = WARN) @Message(id = 109, value = "SSL socket is required by server but secure connections have not been configured") void cannotCreateSSLSocket(); @Message(id = 110, value = "Client requires SSL but server does not support it") IllegalStateException serverDoesNotSupportSsl(); @Message(id = 111, value = "SSL has not been configured but ssl-port property has been specified - the connection will use clear-text protocol") String sslPortWithoutSslConfiguration(); // @Message(id = 112, value = "Security initializer was set to 'elytron' but no authentication-context has been specified") // OperationFailedException elytronInitializerMissingAuthContext(); @Message(id = 113, value = "Authentication context has been defined but it is ineffective because the security initializer is not set to 'elytron'") OperationFailedException ineffectiveAuthenticationContextConfiguration(); @Message(id = 114, value = "Elytron security initializer not supported in previous iiop-openjdk versions and can't be converted") String elytronInitializerNotSupportedInPreviousVersions(); @Message(id = 115, value = "No IIOP socket bindings have been configured") IllegalStateException noSocketBindingsConfigured(); @LogMessage(level = WARN) @Message(id = 117, value = "CLEARTEXT in IIOP subsystem won't be used because server-requires-ssl parameter have been set to true") void wontUseCleartextSocket(); @Message(id = 118, value = "Legacy security is no longer supported.") IllegalStateException legacySecurityUnsupported(); @Message(id = 119, value = "The use of security realms at runtime is unsupported.") OperationFailedException runtimeSecurityRealmUnsupported(); @Message(id = 120, value = "The use of security domains at runtime is unsupported.") OperationFailedException runtimeSecurityDomainUnsupported(); }
20,051
45.416667
187
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/deployment/IIOPDependencyProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.deployment; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; /** * @author Stuart Douglas */ public class IIOPDependencyProcessor implements DeploymentUnitProcessor { public static final ModuleIdentifier CORBA_ID = ModuleIdentifier.create("org.omg.api"); public static final ModuleIdentifier JAVAX_RMI_API_ID = ModuleIdentifier.create("javax.rmi.api"); public static final ModuleIdentifier IIOP_OPENJDK_ID = ModuleIdentifier.create("javax.orb.api"); @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, CORBA_ID, false, false, false, false)); moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JAVAX_RMI_API_ID, false, false, false, false)); //we need to add iiop, as the orb is initialized from the context class loader of the deployment moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, IIOP_OPENJDK_ID, false, false, false, false)); } }
2,907
51.872727
130
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/deployment/IIOPMarkerProcessor.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.deployment; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; /** * Processor responsible for marking a deployment as using IIOP * * @author Stuart Douglas */ public class IIOPMarkerProcessor implements DeploymentUnitProcessor{ @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); //for now we mark all subsystems as using IIOP if the IIOP subsystem is installed IIOPDeploymentMarker.mark(deploymentUnit); } }
1,832
41.627907
102
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/deployment/IIOPDeploymentMarker.java
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.deployment; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.DeploymentUnit; /** * @author Stuart Douglas */ public class IIOPDeploymentMarker { private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class); public static void mark(final DeploymentUnit deployment) { deployment.putAttachment(ATTACHMENT_KEY, true); } public static boolean isIIOPDeployment(final DeploymentUnit deploymentUnit) { final Boolean val = deploymentUnit.getAttachment(ATTACHMENT_KEY); return val != null && val; } }
1,669
37.837209
101
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/deployment/IIOPClearCachesProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.deployment; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.modules.Module; import org.wildfly.iiop.openjdk.rmi.ExceptionAnalysis; import org.wildfly.iiop.openjdk.rmi.InterfaceAnalysis; import org.wildfly.iiop.openjdk.rmi.ValueAnalysis; /** * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class IIOPClearCachesProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { } @Override public void undeploy(final DeploymentUnit context) { //clear data from the relevant caches Module module = context.getAttachment(Attachments.MODULE); if(module == null) { return; } ExceptionAnalysis.clearCache(module.getClassLoader()); InterfaceAnalysis.clearCache(module.getClassLoader()); ValueAnalysis.clearCache(module.getClassLoader()); } }
2,280
39.017544
102
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/BindingIteratorImpl.java
package org.wildfly.iiop.openjdk.naming; /* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.omg.CORBA.UserException; import org.omg.CosNaming.Binding; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Implementation of the "BindingIterator" interface * * @author Gerald Brose */ public class BindingIteratorImpl extends org.omg.CosNaming.BindingIteratorPOA { Binding[] bindings; int iterator_pos = 0; public BindingIteratorImpl(Binding[] b) { bindings = b; if (b.length > 0) iterator_pos = 0; } public void destroy() { bindings = null; try { _poa().deactivate_object(_poa().servant_to_id(this)); } catch (UserException e) { throw IIOPLogger.ROOT_LOGGER.exceptionDestroingIterator(e.getMessage()); } } public boolean next_n(int how_many, org.omg.CosNaming.BindingListHolder bl) { int diff = bindings.length - iterator_pos; if (diff > 0) { Binding[] bndgs = null; if (how_many <= diff) { bndgs = new Binding[how_many]; System.arraycopy(bindings, iterator_pos, bndgs, 0, how_many); iterator_pos += how_many; } else { bndgs = new Binding[diff]; System.arraycopy(bindings, iterator_pos, bndgs, 0, diff); iterator_pos = bindings.length; } bl.value = bndgs; return true; } else { bl.value = new Binding[0]; return false; } } public boolean next_one(org.omg.CosNaming.BindingHolder b) { if (iterator_pos < bindings.length) { b.value = bindings[iterator_pos++]; return true; } else { b.value = new Binding(new org.omg.CosNaming.NameComponent[0], org.omg.CosNaming.BindingType.nobject); return false; } } }
3,109
34.747126
113
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/Name.java
package org.wildfly.iiop.openjdk.naming; /* * JacORB - a free Java ORB * * Copyright (C) 1997-2004 Gerald Brose. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ import java.util.Vector; import org.omg.CORBA.INTERNAL; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContextPackage.InvalidName; /** * A convenience class for names and converting between Names and their string representation * * @author Gerald Brose, FU Berlin */ public class Name implements java.io.Serializable { private NameComponent[] fullName; private NameComponent baseName; /** context part of this Name */ private NameComponent[] ctxName; public Name() { fullName = null; baseName = null; ctxName = null; } /** * create a name from an array of NameComponents */ public Name(NameComponent[] n) throws InvalidName { if (n == null || n.length == 0) throw new InvalidName(); fullName = n; baseName = n[n.length - 1]; if (n.length > 1) { ctxName = new NameComponent[n.length - 1]; for (int i = 0; i < n.length - 1; i++) ctxName[i] = n[i]; } else ctxName = null; } /** * create a name from a stringified name */ public Name(String string_name) throws InvalidName { this(toName(string_name)); } /** * create a name from a singleNameComponent */ public Name(NameComponent n) throws InvalidName { if (n == null) throw new InvalidName(); baseName = n; fullName = new NameComponent[1]; fullName[0] = n; ctxName = null; } /** * @return a NameComponent object representing the unstructured base name of this structured name */ public NameComponent baseNameComponent() { return baseName; } public String kind() { return baseName.kind; } /** * @return this name as an array of org.omg.CosNaming.NameComponent, neccessary for a number of operations on naming context */ public NameComponent[] components() { return fullName; } /** * @return a Name object representing the name of the enclosing context */ public Name ctxName() { // null if no further context if (ctxName != null) { try { return new Name(ctxName); } catch (InvalidName e) { throw new INTERNAL(e.toString()); } } return null; } public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Name)) return false; return (toString().equals(obj.toString())); } public Name fullName() throws InvalidName { return new Name(fullName); } public int hashCode() { return toString().hashCode(); } /** * @return the string representation of this name */ public String toString() { try { return toString(fullName); } catch (InvalidName in) { return "<invalid>"; } } /** * @return a single NameComponent, parsed from sn */ private static NameComponent getComponent(String sn) throws InvalidName { char ch; int len = sn.length(); boolean inKind = false; StringBuffer id = new StringBuffer(); StringBuffer kind = new StringBuffer(); for (int i = 0; i < len; i++) { ch = sn.charAt(i); if (ch == '\\') { // Escaped character i++; if (i >= len) { throw new InvalidName(); } ch = sn.charAt(i); } else if (ch == '.') { // id/kind separator character if (inKind) { throw new InvalidName(); } inKind = true; continue; } if (inKind) { kind.append(ch); } else { id.append(ch); } } return (new NameComponent(id.toString(), kind.toString())); } /** * * @return an a array of NameComponents * @throws InvalidName */ public static NameComponent[] toName(String sn) throws InvalidName { if (sn == null || sn.length() == 0 || sn.startsWith("/")) throw new InvalidName(); Vector v = new Vector(); int start = 0; int i = 0; for (; i < sn.length(); i++) { if (sn.charAt(i) == '/' && sn.charAt(i - 1) != '\\') { if (i - start == 0) throw new InvalidName(); v.addElement(getComponent(sn.substring(start, i))); start = i + 1; } } if (start < i) v.addElement(getComponent(sn.substring(start, i))); NameComponent[] result = new NameComponent[v.size()]; for (int j = 0; j < result.length; j++) { result[j] = (NameComponent) v.elementAt(j); } return result; } /** * @return the string representation of this NameComponent array */ public static String toString(NameComponent[] n) throws InvalidName { if (n == null || n.length == 0) throw new InvalidName(); StringBuffer b = new StringBuffer(); for (int i = 0; i < n.length; i++) { if (i > 0) b.append("/"); if (n[i].id.length() > 0) b.append(escape(n[i].id)); if (n[i].kind.length() > 0 || n[i].id.length() == 0) b.append("."); if (n[i].kind.length() > 0) b.append(escape(n[i].kind)); } return b.toString(); } /** * escape any occurrence of "/", "." and "\" */ private static String escape(String s) { StringBuffer sb = new StringBuffer(s); for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) == '/' || sb.charAt(i) == '\\' || sb.charAt(i) == '.') { sb.insert(i, '\\'); i++; } } return sb.toString(); } }
7,061
25.449438
128
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/CorbaNamingContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.naming; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import org.omg.CORBA.INTERNAL; import org.omg.CORBA.ORB; import org.omg.CosNaming.Binding; import org.omg.CosNaming.BindingIteratorHelper; import org.omg.CosNaming.BindingIteratorHolder; import org.omg.CosNaming.BindingListHolder; import org.omg.CosNaming.BindingType; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextExtHelper; import org.omg.CosNaming.NamingContextExtPOA; import org.omg.CosNaming.NamingContextExtPackage.InvalidAddress; import org.omg.CosNaming.NamingContextPackage.AlreadyBound; import org.omg.CosNaming.NamingContextPackage.CannotProceed; import org.omg.CosNaming.NamingContextPackage.InvalidName; import org.omg.CosNaming.NamingContextPackage.NotEmpty; import org.omg.CosNaming.NamingContextPackage.NotFound; import org.omg.CosNaming.NamingContextPackage.NotFoundReason; import org.omg.PortableServer.POA; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * <p> * This class implements an in-VM CORBA Naming Server that caches for JBoss to use. All contexts keep a cache of the * local sub-contexts to avoid unnecessary remote calls when resolving a complex name. * </p> * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class CorbaNamingContext extends NamingContextExtPOA implements Serializable { private static final long serialVersionUID = 132820915998903191L; /** * static references to the running ORB and root POA. */ private static ORB orb; private static POA rootPoa; /** * the naming service POA - i.e. the POA that activates all naming contexts. */ private transient POA poa; /** * table of all name bindings in this contexts, ie. name -> obj ref. */ private Map<Name, Object> names = new Hashtable<Name, Object>(); /** * table of all subordinate naming contexts, ie. name -> obj ref. */ private Map<Name, Object> contexts = new Hashtable<Name, Object>(); /** * cache of all active naming context implementations - used when resolving contexts recursively to avoid * unnecessary remote calls that may lead to thread pool depletion. */ private static Map<String, CorbaNamingContext> contextImpls = new Hashtable<String, CorbaNamingContext>(); /** * no tests of bound objects for existence */ private boolean noPing = false; /** * purge? */ private boolean doPurge = false; private boolean destroyed = false; private int childCount = 0; //======================================= Initialization Methods ==================================// /** * <p> * This method needs to be called once to initialize the static fields orb and rootPoa. * </p> * * @param orb a reference to the running {@code ORB} instance. * @param rootPoa a reference to the root {@code POA}. */ public static void init(ORB orb, POA rootPoa) { CorbaNamingContext.orb = orb; CorbaNamingContext.rootPoa = rootPoa; } /** * <p> * This method needs to be called for each newly created or re-read naming context to set its POA. * </p> * * @param poa a reference to the Naming Service {@code POA}. * @param doPurge a boolean that indicates if dead objects should be purged from the context ({@code true}) upon cleanup * or not ({@code false}). * @param noPing a boolean that indicates if the method {@code resolve} should check if the resolved name or context is * alive before returning it. If {@code false}, the name will be checked (default) */ public void init(POA poa, boolean doPurge, boolean noPing) { this.poa = poa; this.doPurge = doPurge; this.noPing = noPing; } //======================================= NamingContextOperation Methods ==================================// public void bind(NameComponent[] nc, org.omg.CORBA.Object obj) throws NotFound, CannotProceed, InvalidName, AlreadyBound { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); if (obj == null) throw new org.omg.CORBA.BAD_PARAM(); Name n = new Name(nc); Name ctx = n.ctxName(); NameComponent nb = n.baseNameComponent(); if (ctx == null) { if (this.names.containsKey(n)) { // if the name is still in use, try to ping the object org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.names.get(n); if (isDead(ref)) { rebind(n.components(), obj); return; } throw new AlreadyBound(); } else if (this.contexts.containsKey(n)) { // if the name is still in use, try to ping the object org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.contexts.get(n); if (isDead(ref)) unbind(n.components()); throw new AlreadyBound(); } if ((this.names.put(n, obj)) != null) throw new CannotProceed(_this(), n.components()); IIOPLogger.ROOT_LOGGER.debugf("Bound name: %s", n); } else { NameComponent[] ncx = new NameComponent[]{nb}; org.omg.CORBA.Object context = this.resolve(ctx.components()); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) jbossContext.bind(ncx, obj); else NamingContextExtHelper.narrow(context).bind(ncx, obj); } } public void bind_context(NameComponent[] nc, NamingContext obj) throws NotFound, CannotProceed, InvalidName, AlreadyBound { if (this.destroyed) throw new CannotProceed(); Name n = new Name(nc); Name ctx = n.ctxName(); NameComponent nb = n.baseNameComponent(); if (ctx == null) { if (this.names.containsKey(n)) { // if the name is still in use, try to ping the object org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.names.get(n); if (isDead(ref)) unbind(n.components()); else throw new AlreadyBound(); } else if (this.contexts.containsKey(n)) { // if the name is still in use, try to ping the object org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.contexts.get(n); if (isDead(ref)) { rebind_context(n.components(), obj); return; } throw new AlreadyBound(); } if ((this.contexts.put(n, obj)) != null) throw new CannotProceed(_this(), n.components()); IIOPLogger.ROOT_LOGGER.debugf("Bound context: %s", n); } else { NameComponent[] ncx = new NameComponent[]{nb}; org.omg.CORBA.Object context = this.resolve(ctx.components()); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) jbossContext.bind_context(ncx, obj); else NamingContextExtHelper.narrow(context).bind_context(ncx, obj); } } public NamingContext bind_new_context(NameComponent[] nc) throws NotFound, CannotProceed, InvalidName, AlreadyBound { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); NamingContext context = new_context(); if (context == null) throw new CannotProceed(); bind_context(nc, context); return context; } public void destroy() throws NotEmpty { if (this.destroyed) return; if (!this.names.isEmpty() || !this.contexts.isEmpty()) throw new NotEmpty(); else { this.names = null; this.contexts = null; this.destroyed = true; } } public void list(int how_many, BindingListHolder bl, BindingIteratorHolder bi) { if (this.destroyed) return; Binding[] result; this.cleanup(); int size = how_many(); Iterator<Name> names = this.names.keySet().iterator(); Iterator<Name> contexts = this.contexts.keySet().iterator(); if (how_many < size) { // counter for copies int how_many_ctr = how_many; // set up an array with "how_many" bindings result = new Binding[how_many]; for (; names.hasNext() && how_many_ctr > 0; how_many_ctr--) result[how_many_ctr - 1] = new Binding((names.next()).components(), BindingType.nobject); for (; contexts.hasNext() && how_many_ctr > 0; how_many_ctr--) result[how_many_ctr - 1] = new Binding((contexts.next()).components(), BindingType.ncontext); // create a new BindingIterator for the remaining arrays size -= how_many; Binding[] rest = new Binding[size]; for (; names.hasNext() && size > 0; size--) rest[size - 1] = new Binding((names.next()).components(), BindingType.nobject); for (; contexts.hasNext() && size > 0; size--) rest[size - 1] = new Binding((contexts.next()).components(), BindingType.ncontext); org.omg.CORBA.Object o; try { // Iterators are activated with the RootPOA (transient) byte[] oid = rootPoa.activate_object(new BindingIteratorImpl(rest)); o = rootPoa.id_to_reference(oid); } catch (Exception e) { IIOPLogger.ROOT_LOGGER.logInternalError(e); throw new INTERNAL(e.toString()); } bi.value = BindingIteratorHelper.narrow(o); } else { result = new Binding[size]; for (; names.hasNext() && size > 0; size--) result[size - 1] = new Binding((names.next()).components(), BindingType.nobject); for (; contexts.hasNext() && size > 0; size--) result[size - 1] = new Binding((contexts.next()).components(), BindingType.ncontext); } bl.value = result; } public NamingContext new_context() { try { // create and initialize a new context. CorbaNamingContext newContextImpl = new CorbaNamingContext(); newContextImpl.init(this.poa, this.doPurge, this.noPing); // create the oid for the new context and activate it with the naming service POA. String oid = new String(this.poa.servant_to_id(this), StandardCharsets.UTF_8) + "/ctx" + (++this.childCount); this.poa.activate_object_with_id(oid.getBytes(StandardCharsets.UTF_8), newContextImpl); // add the newly-created context to the cache. contextImpls.put(oid, newContextImpl); return NamingContextExtHelper.narrow(this.poa.create_reference_with_id(oid.getBytes(StandardCharsets.UTF_8), "IDL:omg.org/CosNaming/NamingContextExt:1.0")); } catch (Exception e) { IIOPLogger.ROOT_LOGGER.failedToCreateNamingContext(e); return null; } } public void rebind(NameComponent[] nc, org.omg.CORBA.Object obj) throws NotFound, CannotProceed, InvalidName { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); if (obj == null) throw new org.omg.CORBA.BAD_PARAM(); Name n = new Name(nc); Name ctx = n.ctxName(); NameComponent nb = n.baseNameComponent(); if (ctx == null) { // the name is bound, but it is bound to a context - the client should have been using rebind_context! if (this.contexts.containsKey(n)) throw new NotFound(NotFoundReason.not_object, new NameComponent[]{nb}); // try remove an existing binding. org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.names.remove(n); if (ref != null) ref._release(); // do the rebinding in this context this.names.put(n, obj); IIOPLogger.ROOT_LOGGER.debugf("Bound name: %s", n); } else { // rebind in the correct context NameComponent[] ncx = new NameComponent[]{nb}; org.omg.CORBA.Object context = this.resolve(ctx.components()); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) jbossContext.rebind(ncx, obj); else NamingContextExtHelper.narrow(context).rebind(ncx, obj); } } public void rebind_context(NameComponent[] nc, NamingContext obj) throws NotFound, CannotProceed, InvalidName { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); if (obj == null) throw new org.omg.CORBA.BAD_PARAM(); Name n = new Name(nc); Name ctx = n.ctxName(); NameComponent nb = n.baseNameComponent(); if (ctx == null) { // the name is bound, but it is bound to an object - the client should have been using rebind(). if (this.names.containsKey(n)) throw new NotFound(NotFoundReason.not_context, new NameComponent[]{nb}); // try to remove an existing context binding. org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.contexts.remove(n); if (ref != null) { ref._release(); // remove the old context from the implementation cache. String oid = this.getObjectOID(ref); if (oid != null) contextImpls.remove(oid); } this.contexts.put(n, obj); IIOPLogger.ROOT_LOGGER.debugf("Bound context: %s", n.baseNameComponent().id); } else { // rebind in the correct context NameComponent[] ncx = new NameComponent[]{nb}; org.omg.CORBA.Object context = this.resolve(ctx.components()); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) jbossContext.rebind_context(ncx, obj); else NamingContextExtHelper.narrow(context).rebind_context(ncx, obj); } } public org.omg.CORBA.Object resolve(NameComponent[] nc) throws NotFound, CannotProceed, InvalidName { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); Name n = new Name(nc[0]); if (nc.length > 1) { org.omg.CORBA.Object next_context = (org.omg.CORBA.Object) this.contexts.get(n); if ((next_context == null) || (isDead(next_context))) throw new NotFound(NotFoundReason.missing_node, nc); NameComponent[] nc_prime = new NameComponent[nc.length - 1]; System.arraycopy(nc, 1, nc_prime, 0, nc_prime.length); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(next_context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) return jbossContext.resolve(nc_prime); else return NamingContextExtHelper.narrow(next_context).resolve(nc_prime); } else { org.omg.CORBA.Object result = (org.omg.CORBA.Object) this.contexts.get(n); if (result == null) result = (org.omg.CORBA.Object) this.names.get(n); if (result == null) throw new NotFound(NotFoundReason.missing_node, n.components()); if (!noPing && isDead(result)) throw new NotFound(NotFoundReason.missing_node, n.components()); return result; } } public void unbind(NameComponent[] nc) throws NotFound, CannotProceed, InvalidName { if (this.destroyed) throw new CannotProceed(); if (nc == null || nc.length == 0) throw new InvalidName(); Name n = new Name(nc); Name ctx = n.ctxName(); NameComponent nb = n.baseNameComponent(); if (ctx == null) { if (this.names.containsKey(n)) { org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.names.remove(n); ref._release(); IIOPLogger.ROOT_LOGGER.debugf("Unbound: %s", n); } else if (this.contexts.containsKey(n)) { org.omg.CORBA.Object ref = (org.omg.CORBA.Object) this.contexts.remove(n); ref._release(); // remove the context from the implementation cache. String oid = this.getObjectOID(ref); if (oid != null) contextImpls.remove(oid); IIOPLogger.ROOT_LOGGER.debugf("Unbound: %s", n); } else { IIOPLogger.ROOT_LOGGER.failedToUnbindObject(n); throw new NotFound(NotFoundReason.not_context, n.components()); } } else { NameComponent[] ncx = new NameComponent[]{nb}; org.omg.CORBA.Object context = this.resolve(ctx.components()); // try first to call the context implementation object directly. String contextOID = this.getObjectOID(context); CorbaNamingContext jbossContext = (contextOID == null ? null : contextImpls.get(contextOID)); if (jbossContext != null) jbossContext.unbind(ncx); else NamingContextExtHelper.narrow(context).unbind(ncx); } } //======================================= NamingContextExtOperations Methods ==================================// public org.omg.CORBA.Object resolve_str(String n) throws NotFound, CannotProceed, InvalidName { return resolve(to_name(n)); } public NameComponent[] to_name(String sn) throws InvalidName { return Name.toName(sn); } public String to_string(NameComponent[] n) throws InvalidName { return Name.toString(n); } public String to_url(String addr, String sn) throws InvalidAddress, InvalidName { return null; } //======================================= Private Helper Methods ==================================// /** * <p> * Cleanup bindings, i.e. ping every object and remove bindings to non-existent objects. * </p> */ private void cleanup() { // Check if object purging enabled if (!this.doPurge) return; for (Map.Entry<Name, Object> entry : this.names.entrySet()) { if (isDead(((org.omg.CORBA.Object) entry.getValue()))) { this.names.remove(entry.getKey()); } } for (Map.Entry<Name, Object> entry : this.contexts.entrySet()) { org.omg.CORBA.Object object = (org.omg.CORBA.Object) entry.getValue(); if (isDead(object)) { this.contexts.remove(entry.getKey()); String oid = this.getObjectOID(object); if (oid != null) contextImpls.remove(oid); } } } /** * <p> * Obtains the OID of the specified CORBA object. * </p> * * @param object the CORBA object whose OID is to be extracted. * @return a {@code String} representing the object OID or null if the method is unable to obtain the object OID. */ private String getObjectOID(org.omg.CORBA.Object object) { String oid = null; try { byte[] oidBytes = this.poa.reference_to_id(object); if (oidBytes != null) oid = new String(oidBytes, StandardCharsets.UTF_8); } catch (Exception e) { IIOPLogger.ROOT_LOGGER.debug("Unable to obtain id from object", e); } return oid; } /** * <p> * Obtains the number of bindings in this context. * </p> * * @return the number of bindings in this context */ private int how_many() { if (this.destroyed) return 0; return this.names.size() + this.contexts.size(); } /** * <p> * Determines if the supplied object is non_existent * </p> * * @param o the CORBA object being verified. * @return {@code true} if the object is non-existent; {@code false} otherwise. */ private boolean isDead(org.omg.CORBA.Object o) { boolean non_exist; try { non_exist = o._non_existent(); } catch (org.omg.CORBA.SystemException e) { non_exist = true; } return non_exist; } /** * <p> * Overrides readObject in Serializable. * </p> * * @param in the {@code InputStream} used to read the objects. * @throws Exception if an error occurs while reading the objects from the stream. */ private void readObject(ObjectInputStream in) throws Exception { in.defaultReadObject(); /** * Recreate tables. For serialization, object references have been transformed into strings */ for (Name key : this.contexts.keySet()) { String ref = (String) this.contexts.remove(key); this.contexts.put(key, orb.string_to_object(ref)); } for (Name key : this.names.keySet()) { String ref = (String) this.names.remove(key); this.names.put(key, orb.string_to_object(ref)); } } /** * <p> * Overrides writeObject in Serializable. * </p> * * @param out the {@code OutputStream} where the objects will be written. * @throws IOException if an error occurs while writing the objects to the stream. */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { /* * For serialization, object references are transformed into strings */ for (Name key : this.contexts.keySet()) { org.omg.CORBA.Object o = (org.omg.CORBA.Object) this.contexts.remove(key); this.contexts.put(key, orb.object_to_string(o)); } for (Name key : this.names.keySet()) { org.omg.CORBA.Object o = (org.omg.CORBA.Object) this.names.remove(key); this.names.put(key, orb.object_to_string(o)); } out.defaultWriteObject(); } }
25,019
37.082192
124
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/WrapperInitialContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.util.Hashtable; import javax.naming.Binding; import javax.naming.Context; import javax.naming.Name; import javax.naming.NameClassPair; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import com.sun.corba.se.impl.orbutil.ORBConstants; /** * @author Stuart Douglas */ public class WrapperInitialContext implements Context { private final Hashtable<Object,Object> environment; @SuppressWarnings("unchecked") public WrapperInitialContext(final Hashtable<Object,Object> environment) { if (environment != null) { this.environment = (Hashtable<Object,Object>) environment.clone(); } else { this.environment = null; } } @Override public Object lookup(final Name name) throws NamingException { return lookup(name.toString()); } @Override public Object lookup(final String name) throws NamingException { try { final int index = name.indexOf('#'); if (index != -1) { final String server = name.substring(0, index); final String lookup = name.substring(index + 1); @SuppressWarnings("unchecked") final Hashtable<Object,Object> environment = (Hashtable<Object,Object>) this.environment.clone(); environment.put(Context.PROVIDER_URL, server); environment.put(ORBConstants.ORB_SERVER_ID_PROPERTY, "1"); return CNCtxFactory.INSTANCE.getInitialContext(environment).lookup(lookup); } else { return CNCtxFactory.INSTANCE.getInitialContext(environment).lookup(name); } } catch (NamingException e) { throw e; } catch (Exception e) { throw new NamingException(e.getMessage()); } } @Override public void bind(final Name name, final Object obj) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).bind(name, obj); } @Override public void bind(final String name, final Object obj) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).bind(name, obj); } @Override public void rebind(final Name name, final Object obj) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).rebind(name, obj); } @Override public void rebind(final String name, final Object obj) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).rebind(name, obj); } @Override public void unbind(final Name name) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).unbind(name); } @Override public void unbind(final String name) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).unbind(name); } @Override public void rename(final Name oldName, final Name newName) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).rename(oldName, newName); } @Override public void rename(final String oldName, final String newName) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).rename(oldName, newName); } @Override public NamingEnumeration<NameClassPair> list(final Name name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).list(name); } @Override public NamingEnumeration<NameClassPair> list(final String name) throws NamingException { return null; } @Override public NamingEnumeration<Binding> listBindings(final Name name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).listBindings(name); } @Override public NamingEnumeration<Binding> listBindings(final String name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).listBindings(name); } @Override public void destroySubcontext(final Name name) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).destroySubcontext(name); } @Override public void destroySubcontext(final String name) throws NamingException { CNCtxFactory.INSTANCE.getInitialContext(environment).destroySubcontext(name); } @Override public Context createSubcontext(final Name name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).createSubcontext(name); } @Override public Context createSubcontext(final String name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).createSubcontext(name); } @Override public Object lookupLink(final Name name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).lookupLink(name); } @Override public Object lookupLink(final String name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).lookupLink(name); } @Override public NameParser getNameParser(final Name name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).getNameParser(name); } @Override public NameParser getNameParser(final String name) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).getNameParser(name); } @Override public Name composeName(final Name name, final Name prefix) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).composeName(name, prefix); } @Override public String composeName(final String name, final String prefix) throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).composeName(name, prefix); } @Override public Object addToEnvironment(final String propName, final Object propVal) throws NamingException { return environment.put(propName, propVal); } @Override public Object removeFromEnvironment(final String propName) throws NamingException { return environment.remove(propName); } @Override public Hashtable<?, ?> getEnvironment() throws NamingException { return environment; } @Override public void close() throws NamingException { } @Override public String getNameInNamespace() throws NamingException { return CNCtxFactory.INSTANCE.getInitialContext(environment).getNameInNamespace(); } }
7,728
34.454128
113
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CNCtx.java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import javax.naming.CannotProceedException; import javax.naming.CompositeName; import javax.naming.ConfigurationException; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.NotContextException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.spi.NamingManager; import javax.naming.spi.ResolveResult; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.ORB; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextHelper; import org.omg.CosNaming.NamingContextPackage.NotFound; import org.omg.CosNaming.NamingContextPackage.NotFoundReason; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.service.CorbaORBService; // Needed for creating default ORB /** * Provides a bridge to the CosNaming server provided by * JavaIDL. This class provides the InitialContext from CosNaming. * * @author Raj Krishnamurthy * @author Rosanna Lee */ public class CNCtx implements javax.naming.Context { ORB _orb; // used by ExceptionMapper and RMI/IIOP factory public NamingContext _nc; // public for accessing underlying NamingContext private NameComponent[] _name = null; Hashtable _env; // used by ExceptionMapper static final CNNameParser parser = new CNNameParser(); private static final String FED_PROP = "com.sun.jndi.cosnaming.federation"; boolean federation = false; /** * Create a CNCtx object. Gets the initial naming * reference for the COS Naming Service from the ORB. * The ORB can be passed in via the java.naming.corba.orb property * or be created using properties in the environment properties. * * @param env Environment properties for initializing name service. * @throws NamingException Cannot initialize ORB or naming context. */ CNCtx(Hashtable env) throws NamingException { if (env != null) { env = (Hashtable) env.clone(); } _env = env; federation = "true".equals(env != null ? env.get(FED_PROP) : null); initOrbAndRootContext(env); } private CNCtx() { } /** * This method is used by the iiop and iiopname URL Context factories. */ public static ResolveResult createUsingURL(String url, Hashtable env) throws NamingException { CNCtx ctx = new CNCtx(); if (env != null) { env = (Hashtable) env.clone(); } ctx._env = env; String rest = ctx.initUsingUrl(env != null ? (ORB) env.get("java.naming.corba.orb") : null, url, env); // rest is the INS name // Return the parsed form to prevent subsequent lookup // from parsing the string as a composite name // The caller should be aware that a toString() of the name // will yield its INS syntax, rather than a composite syntax return new ResolveResult(ctx, parser.parse(rest)); } /** * Creates a CNCtx object which supports the javax.naming * apis given a COS Naming Context object. * * @param orb The ORB used by this context * @param nctx The COS NamingContext object associated with this context * @param name The name of this context relative to the root * @throws ConfigurationException if both the ORB and naming context are null. */ CNCtx(ORB orb, NamingContext nctx, Hashtable env, NameComponent[] name) throws NamingException { if (orb == null || nctx == null) throw IIOPLogger.ROOT_LOGGER.errorConstructingCNCtx(); _orb = orb; _nc = nctx; _env = env; _name = name; federation = "true".equals(env != null ? env.get(FED_PROP) : null); } NameComponent[] makeFullName(NameComponent[] child) { if (_name == null || _name.length == 0) { return child; } NameComponent[] answer = new NameComponent[_name.length + child.length]; // parent System.arraycopy(_name, 0, answer, 0, _name.length); // child System.arraycopy(child, 0, answer, _name.length, child.length); return answer; } public String getNameInNamespace() throws NamingException { if (_name == null || _name.length == 0) { return ""; } return CNNameParser.cosNameToInsString(_name); } /** * These are the URL schemes that need to be processed. * IOR and corbaloc URLs can be passed directly to ORB.string_to_object() */ private static boolean isCorbaUrl(String url) { return url.startsWith("iiop://") || url.startsWith("iiopname://") || url.startsWith("corbaname:"); } /** * Initializes the COS Naming Service. * This method initializes the three instance fields: * _nc : The root naming context. * _orb: The ORB to use for connecting RMI/IIOP stubs and for * getting the naming context (_nc) if one was not specified * explicitly via PROVIDER_URL. * _name: The name of the root naming context. * <p/> * _orb is obtained from java.naming.corba.orb if it has been set. * Otherwise, _orb is created using the host/port from PROVIDER_URL * (if it contains an "iiop" or "iiopname" URL), or from initialization * properties specified in env. * <p/> * _nc is obtained from the IOR stored in PROVIDER_URL if it has been * set and does not contain an "iiop" or "iiopname" URL. It can be * a stringified IOR, "corbaloc" URL, "corbaname" URL, * or a URL (such as file/http/ftp) to a location * containing a stringified IOR. If PROVIDER_URL has not been * set in this way, it is obtained from the result of * ORB.resolve_initial_reference("NameService"); * <p/> * _name is obtained from the "iiop", "iiopname", or "corbaname" URL. * It is the empty name by default. * * @param env Environment The possibly null environment. * @throws NamingException When an error occurs while initializing the * ORB or the naming context. */ private void initOrbAndRootContext(Hashtable env) throws NamingException { ORB inOrb = null; String ncIor = null; if (env != null) { inOrb = (ORB) env.get("java.naming.corba.orb"); } // Extract PROVIDER_URL from environment String provUrl = null; if (env != null) { provUrl = (String) env.get(javax.naming.Context.PROVIDER_URL); } if (provUrl != null && !isCorbaUrl(provUrl)) { // Initialize the root naming context by using the IOR supplied // in the PROVIDER_URL ncIor = getStringifiedIor(provUrl); if (inOrb == null) { // no ORB instance specified; create one using env and defaults inOrb = CorbaORBService.getCurrent(); } setOrbAndRootContext(inOrb, ncIor); } else if (provUrl != null) { // Initialize the root naming context by using the URL supplied // in the PROVIDER_URL String insName = initUsingUrl(inOrb, provUrl, env); // If name supplied in URL, resolve it to a NamingContext if (insName.length() > 0) { _name = parser.nameToCosName(parser.parse(insName)); try { org.omg.CORBA.Object obj = _nc.resolve(_name); _nc = NamingContextHelper.narrow(obj); if (_nc == null) { throw IIOPLogger.ROOT_LOGGER.notANamingContext(insName); } } catch (BAD_PARAM e) { throw IIOPLogger.ROOT_LOGGER.notANamingContext(insName); } catch (Exception e) { throw ExceptionMapper.mapException(e, this, _name); } } } else { // No PROVIDER_URL supplied; initialize using defaults if (inOrb == null) { // No ORB instance specified; create one using env and defaults inOrb = CorbaORBService.getCurrent(); IIOPLogger.ROOT_LOGGER.debugf("Getting default ORB %s", inOrb); } setOrbAndRootContext(inOrb, (String) null); } } private String initUsingUrl(ORB orb, String url, Hashtable env) throws NamingException { if (url.startsWith("iiop://") || url.startsWith("iiopname://")) { return initUsingIiopUrl(orb, url, env); } else { return initUsingCorbanameUrl(orb, url, env); } } /** * Handles "iiop" and "iiopname" URLs (INS 98-10-11) */ private String initUsingIiopUrl(ORB defOrb, String url, Hashtable env) throws NamingException { try { IiopUrl parsedUrl = new IiopUrl(url); Vector addrs = parsedUrl.getAddresses(); IiopUrl.Address addr; NamingException savedException = null; for (int i = 0; i < addrs.size(); i++) { addr = (IiopUrl.Address) addrs.elementAt(i); try { if (defOrb != null) { try { String tmpUrl = "corbaloc:iiop:" + addr.host + ":" + addr.port + "/NameService"; org.omg.CORBA.Object rootCtx = defOrb.string_to_object(tmpUrl); setOrbAndRootContext(defOrb, rootCtx); return parsedUrl.getStringName(); } catch (Exception e) { } // keep going } // Get ORB ORB orb = CorbaUtils.getOrb(addr.host, addr.port, env); // Assign to fields setOrbAndRootContext(orb, (String) null); return parsedUrl.getStringName(); } catch (NamingException ne) { savedException = ne; } } if (savedException != null) { throw savedException; } else { throw IIOPLogger.ROOT_LOGGER.invalidURLOrIOR(url); } } catch (MalformedURLException e) { throw new ConfigurationException(e.getMessage()); } } /** * Initializes using "corbaname" URL (INS 99-12-03) */ private String initUsingCorbanameUrl(ORB orb, String url, Hashtable env) throws NamingException { try { CorbanameUrl parsedUrl = new CorbanameUrl(url); String corbaloc = parsedUrl.getLocation(); String cosName = parsedUrl.getStringName(); if (orb == null) { // No ORB instance specified; create one using env and defaults orb = CorbaORBService.getCurrent(); } setOrbAndRootContext(orb, corbaloc); return parsedUrl.getStringName(); } catch (MalformedURLException e) { throw new ConfigurationException(e.getMessage()); } } private void setOrbAndRootContext(ORB orb, String ncIor) throws NamingException { _orb = orb; try { org.omg.CORBA.Object ncRef; if (ncIor != null) { ncRef = _orb.string_to_object(ncIor); } else { ncRef = _orb.resolve_initial_references("NameService"); } _nc = NamingContextHelper.narrow(ncRef); if (_nc == null) { if (ncIor != null) { throw IIOPLogger.ROOT_LOGGER.errorConvertingIORToNamingCtx(ncIor); } else { throw IIOPLogger.ROOT_LOGGER.errorResolvingNSInitRef(); } } } catch (org.omg.CORBA.ORBPackage.InvalidName in) { NamingException ne = IIOPLogger.ROOT_LOGGER.cosNamingNotRegisteredCorrectly(); ne.setRootCause(in); throw ne; } catch (org.omg.CORBA.COMM_FAILURE e) { NamingException ne = IIOPLogger.ROOT_LOGGER.errorConnectingToORB(); ne.setRootCause(e); throw ne; } catch (BAD_PARAM e) { NamingException ne = IIOPLogger.ROOT_LOGGER.invalidURLOrIOR(ncIor); ne.setRootCause(e); throw ne; } catch (org.omg.CORBA.INV_OBJREF e) { NamingException ne = IIOPLogger.ROOT_LOGGER.invalidObjectReference(ncIor); ne.setRootCause(e); throw ne; } } private void setOrbAndRootContext(ORB orb, org.omg.CORBA.Object ncRef) throws NamingException { _orb = orb; try { _nc = NamingContextHelper.narrow(ncRef); if (_nc == null) { throw IIOPLogger.ROOT_LOGGER.errorConvertingIORToNamingCtx(ncRef.toString()); } } catch (org.omg.CORBA.COMM_FAILURE e) { NamingException ne = IIOPLogger.ROOT_LOGGER.errorConnectingToORB(); ne.setRootCause(e); throw ne; } } private String getStringifiedIor(String url) throws NamingException { if (url.startsWith("IOR:") || url.startsWith("corbaloc:")) { return url; } else { InputStream in = null; Throwable originalException = null; String retValue = null; try { URL u = new URL(url); in = u.openStream(); if (in != null) { BufferedReader bufin = new BufferedReader(new InputStreamReader(in, StandardCharsets.ISO_8859_1)); String str; while ((str = bufin.readLine()) != null) { if (str.startsWith("IOR:")) { retValue = str; break; } } } } catch (IOException e) { NamingException ne = IIOPLogger.ROOT_LOGGER.invalidURLOrIOR(url); ne.setRootCause(e); originalException = ne; } catch (Throwable ex) { if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } originalException = ex; } finally { Throwable suppressed = originalException; // OK to be null if (in != null) { try { in.close(); } catch (IOException e) { NamingException ne = IIOPLogger.ROOT_LOGGER.invalidURLOrIOR(url); ne.setRootCause(e); if (suppressed != null) { suppressed.addSuppressed(ne); } else { suppressed = ne; } } } if (suppressed != null) { if (suppressed instanceof RuntimeException) { throw (RuntimeException) suppressed; } if (suppressed instanceof Error) { throw (Error) suppressed; } if (suppressed instanceof NamingException) { throw (NamingException) suppressed; } } } if (retValue != null) { return retValue; } } throw IIOPLogger.ROOT_LOGGER.urlDoesNotContainIOR(url); } /** * Does the job of calling the COS Naming API, * resolve, and performs the exception mapping. If the resolved * object is a COS Naming Context (sub-context), then this function * returns a new JNDI naming context object. * * @param path the NameComponent[] object. * @return Resolved object returned by the COS Name Server. * @throws NotFound No objects under the name. * @throws org.omg.CosNaming.NamingContextPackage.CannotProceed Unable to obtain a continuation context * @throws org.omg.CosNaming.NamingContextPackage.InvalidName Name not understood. */ Object callResolve(NameComponent[] path) throws NamingException { try { org.omg.CORBA.Object obj = _nc.resolve(path); try { NamingContext nc = NamingContextHelper.narrow(obj); if (nc != null) { return new CNCtx(_orb, nc, _env, makeFullName(path)); } else { return obj; } } catch (org.omg.CORBA.SystemException e) { return obj; } } catch (Exception e) { throw ExceptionMapper.mapException(e, this, path); } } /** * Converts the "String" name into a CompositeName * returns the object resolved by the COS Naming api, * resolve. Returns the current context if the name is empty. * Returns either an org.omg.CORBA.Object or javax.naming.Context object. * * @param name string used to resolve the object. * @return the resolved object * @throws NamingException See callResolve. */ public Object lookup(String name) throws NamingException { return lookup(new CompositeName(name)); } /** * Converts the "Name" name into a NameComponent[] object and * returns the object resolved by the COS Naming api, * resolve. Returns the current context if the name is empty. * Returns either an org.omg.CORBA.Object or javax.naming.Context object. * * @param name JNDI Name used to resolve the object. * @return the resolved object * @throws NamingException See callResolve. */ public Object lookup(Name name) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(name.toString()); if (name.size() == 0) return this; // %%% should clone() so that env can be changed NameComponent[] path = CNNameParser.nameToCosName(name); try { Object answer = callResolve(path); try { return NamingManager.getObjectInstance(answer, name, this, _env); } catch (NamingException e) { throw e; } catch (Exception e) { NamingException ne = IIOPLogger.ROOT_LOGGER.errorGeneratingObjectViaFactory(); ne.setRootCause(e); throw ne; } } catch (CannotProceedException cpe) { javax.naming.Context cctx = getContinuationContext(cpe); return cctx.lookup(cpe.getRemainingName()); } } /** * Performs bind or rebind in the context depending on whether the * flag rebind is set. The only objects allowed to be bound are of * types org.omg.CORBA.Object, org.omg.CosNaming.NamingContext. * You can use a state factory to turn other objects (such as * Remote) into these acceptable forms. * <p/> * Uses the COS Naming apis bind/rebind or * bind_context/rebind_context. * * @param pth NameComponent[] object * @param obj Object to be bound. * @param rebind perform rebind ? if true performs a rebind. * @throws NotFound No objects under the name. * @throws org.omg.CosNaming.NamingContextPackage.CannotProceed Unable to obtain a continuation context * @throws org.omg.CosNaming.NamingContextPackage.AlreadyBound An object is already bound to this name. */ private void callBindOrRebind(NameComponent[] pth, Name name, Object obj, boolean rebind) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(name.toString()); try { // Call state factories to convert obj = NamingManager.getStateToBind(obj, name, this, _env); if (obj instanceof CNCtx) { // Use naming context object reference obj = ((CNCtx) obj)._nc; } if (obj instanceof NamingContext) { NamingContext nobj = NamingContextHelper.narrow((org.omg.CORBA.Object) obj); if (rebind) _nc.rebind_context(pth, nobj); else _nc.bind_context(pth, nobj); } else if (obj instanceof org.omg.CORBA.Object) { if (rebind) _nc.rebind(pth, (org.omg.CORBA.Object) obj); else _nc.bind(pth, (org.omg.CORBA.Object) obj); } else throw IIOPLogger.ROOT_LOGGER.notACorbaObject(); } catch (BAD_PARAM e) { // probably narrow() failed? NamingException ne = new NotContextException(name.toString()); ne.setRootCause(e); throw ne; } catch (Exception e) { throw ExceptionMapper.mapException(e, this, pth); } } /** * Converts the "Name" name into a NameComponent[] object and * performs the bind operation. Uses callBindOrRebind. Throws an * invalid name exception if the name is empty. We need a name to * bind the object even when we work within the current context. * * @param name JNDI Name object * @param obj Object to be bound. * @throws NamingException See callBindOrRebind */ public void bind(Name name, Object obj) throws NamingException { if (name.size() == 0) { throw IIOPLogger.ROOT_LOGGER.invalidEmptyName(); } NameComponent[] path = CNNameParser.nameToCosName(name); try { callBindOrRebind(path, name, obj, false); } catch (CannotProceedException e) { javax.naming.Context cctx = getContinuationContext(e); cctx.bind(e.getRemainingName(), obj); } } private static javax.naming.Context getContinuationContext(CannotProceedException cpe) throws NamingException { try { return NamingManager.getContinuationContext(cpe); } catch (CannotProceedException e) { Object resObj = e.getResolvedObj(); if (resObj instanceof Reference) { Reference ref = (Reference) resObj; RefAddr addr = ref.get("nns"); if (addr.getContent() instanceof javax.naming.Context) { NamingException ne = IIOPLogger.ROOT_LOGGER.noReferenceFound(); ne.setRootCause(cpe.getRootCause()); throw ne; } } throw e; } } /** * Converts the "String" name into a CompositeName object and * performs the bind operation. Uses callBindOrRebind. Throws an * invalid name exception if the name is empty. * * @param name string * @param obj Object to be bound. * @throws NamingException See callBindOrRebind */ public void bind(String name, Object obj) throws NamingException { bind(new CompositeName(name), obj); } /** * Converts the "Name" name into a NameComponent[] object and * performs the rebind operation. Uses callBindOrRebind. Throws an * invalid name exception if the name is empty. We must have a name * to rebind the object to even if we are working within the current * context. * * @param name string * @param obj Object to be bound. * @throws NamingException See callBindOrRebind */ public void rebind(Name name, Object obj) throws NamingException { if (name.size() == 0) { throw IIOPLogger.ROOT_LOGGER.invalidEmptyName(); } NameComponent[] path = CNNameParser.nameToCosName(name); try { callBindOrRebind(path, name, obj, true); } catch (CannotProceedException e) { javax.naming.Context cctx = getContinuationContext(e); cctx.rebind(e.getRemainingName(), obj); } } /** * Converts the "String" name into a CompositeName object and * performs the rebind operation. Uses callBindOrRebind. Throws an * invalid name exception if the name is an empty string. * * @param name string * @param obj Object to be bound. * @throws NamingException See callBindOrRebind */ public void rebind(String name, Object obj) throws NamingException { rebind(new CompositeName(name), obj); } /** * Calls the unbind api of COS Naming and uses the exception mapper * class to map the exceptions * * @param path NameComponent[] object * @throws NotFound No objects under the name. If leaf * is not found, that's OK according to the JNDI spec * @throws org.omg.CosNaming.NamingContextPackage.CannotProceed Unable to obtain a continuation context * @throws org.omg.CosNaming.NamingContextPackage.InvalidName Name not understood. */ private void callUnbind(NameComponent[] path) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(Arrays.toString(path)); try { _nc.unbind(path); } catch (NotFound e) { // If leaf is the one missing, return success // as per JNDI spec if (leafNotFound(e, path[path.length - 1])) { // do nothing } else { throw ExceptionMapper.mapException(e, this, path); } } catch (Exception e) { throw ExceptionMapper.mapException(e, this, path); } } private boolean leafNotFound(NotFound e, NameComponent leaf) { // This test is not foolproof because some name servers // always just return one component in rest_of_name // so you might not be able to tell whether that is // the leaf (e.g. aa/aa/aa, which one is missing?) NameComponent rest; return e.why.value() == NotFoundReason._missing_node && e.rest_of_name.length == 1 && (rest = e.rest_of_name[0]).id.equals(leaf.id) && (rest.kind == leaf.kind || (rest.kind != null && rest.kind.equals(leaf.kind))); } /** * Converts the "String" name into a CompositeName object and * performs the unbind operation. Uses callUnbind. If the name is * empty, throws an invalid name exception. Do we unbind the * current context (JNDI spec says work with the current context if * the name is empty) ? * * @param name string * @throws NamingException See callUnbind */ public void unbind(String name) throws NamingException { unbind(new CompositeName(name)); } /** * Converts the "Name" name into a NameComponent[] object and * performs the unbind operation. Uses callUnbind. Throws an * invalid name exception if the name is empty. * * @param name string * @throws NamingException See callUnbind */ public void unbind(Name name) throws NamingException { if (name.size() == 0) throw IIOPLogger.ROOT_LOGGER.invalidEmptyName(); NameComponent[] path = CNNameParser.nameToCosName(name); try { callUnbind(path); } catch (CannotProceedException e) { javax.naming.Context cctx = getContinuationContext(e); cctx.unbind(e.getRemainingName()); } } /** * Renames an object. Since COS Naming does not support a rename * api, this method unbinds the object with the "oldName" and * creates a new binding. * * @param oldName string, existing name for the binding. * @param newName string, name used to replace. * @throws NamingException See bind */ public void rename(String oldName, String newName) throws NamingException { rename(new CompositeName(oldName), new CompositeName(newName)); } /** * Renames an object. Since COS Naming does not support a rename * api, this method unbinds the object with the "oldName" and * creates a new binding. * * @param oldName JNDI Name, existing name for the binding. * @param newName JNDI Name, name used to replace. * @throws NamingException See bind */ public void rename(Name oldName, Name newName) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(oldName.toString()); if (oldName.size() == 0 || newName.size() == 0) throw IIOPLogger.ROOT_LOGGER.invalidEmptyName(); Object obj = lookup(oldName); bind(newName, obj); unbind(oldName); } /** * Returns a NameClassEnumeration object which has a list of name * class pairs. Lists the current context if the name is empty. * * @param name string * @return a list of name-class objects as a NameClassEnumeration. * @throws NamingException All exceptions thrown by lookup * with a non-null argument */ public NamingEnumeration list(String name) throws NamingException { return list(new CompositeName(name)); } /** * Returns a NameClassEnumeration object which has a list of name * class pairs. Lists the current context if the name is empty. * * @param name JNDI Name * @return a list of name-class objects as a NameClassEnumeration. * @throws NamingException All exceptions thrown by lookup */ public NamingEnumeration list(Name name) throws NamingException { return listBindings(name); } /** * Returns a BindingEnumeration object which has a list of name * object pairs. Lists the current context if the name is empty. * * @param name string * @return a list of bindings as a BindingEnumeration. * @throws NamingException all exceptions returned by lookup */ public NamingEnumeration listBindings(String name) throws NamingException { return listBindings(new CompositeName(name)); } /** * Returns a BindingEnumeration object which has a list of name * class pairs. Lists the current context if the name is empty. * * @param name JNDI Name * @return a list of bindings as a BindingEnumeration. * @throws NamingException all exceptions returned by lookup. */ public NamingEnumeration listBindings(Name name) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(name.toString()); if (name.size() > 0) { try { Object obj = lookup(name); if (obj instanceof CNCtx) { return new CNBindingEnumeration( (CNCtx) obj, true, _env); } else { throw new NotContextException(name.toString()); } } catch (NamingException ne) { throw ne; } catch (BAD_PARAM e) { NamingException ne = new NotContextException(name.toString()); ne.setRootCause(e); throw ne; } } return new CNBindingEnumeration(this, false, _env); } /** * Calls the destroy on the COS Naming Server * * @param nc The NamingContext object to use. * @throws org.omg.CosNaming.NamingContextPackage.NotEmpty when the context is not empty and cannot be destroyed. */ private void callDestroy(NamingContext nc) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(nc.toString()); try { nc.destroy(); } catch (Exception e) { throw ExceptionMapper.mapException(e, this, null); } } /** * Uses the callDestroy function to destroy the context. If name is * empty destroys the current context. * * @param name string * @throws javax.naming.OperationNotSupportedException when list is invoked * with a non-null argument */ public void destroySubcontext(String name) throws NamingException { destroySubcontext(new CompositeName(name)); } /** * Uses the callDestroy function to destroy the context. Destroys * the current context if name is empty. * * @param name JNDI Name * @throws javax.naming.OperationNotSupportedException when list is invoked * with a non-null argument */ public void destroySubcontext(Name name) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(name.toString()); NamingContext the_nc = _nc; NameComponent[] path = CNNameParser.nameToCosName(name); if (name.size() > 0) { try { javax.naming.Context ctx = (javax.naming.Context) callResolve(path); CNCtx cnc = (CNCtx) ctx; the_nc = cnc._nc; cnc.close(); //remove the reference to the context } catch (ClassCastException e) { throw new NotContextException(name.toString()); } catch (CannotProceedException e) { javax.naming.Context cctx = getContinuationContext(e); cctx.destroySubcontext(e.getRemainingName()); return; } catch (NameNotFoundException e) { // If leaf is the one missing, return success // as per JNDI spec if (e.getRootCause() instanceof NotFound && leafNotFound((NotFound) e.getRootCause(), path[path.length - 1])) { return; // leaf missing OK } throw e; } catch (NamingException e) { throw e; } } callDestroy(the_nc); callUnbind(path); } /** * Calls the bind_new_context COS naming api to create a new subcontext. * * @param path NameComponent[] object * @return the new context object. * @throws NotFound No objects under the name. * @throws org.omg.CosNaming.NamingContextPackage.CannotProceed Unable to obtain a continuation context * @throws org.omg.CosNaming.NamingContextPackage.InvalidName Name not understood. * @throws org.omg.CosNaming.NamingContextPackage.AlreadyBound An object is already bound to this name. */ private javax.naming.Context callBindNewContext(NameComponent[] path) throws NamingException { if (_nc == null) throw IIOPLogger.ROOT_LOGGER.notANamingContext(Arrays.toString(path)); try { NamingContext nctx = _nc.bind_new_context(path); return new CNCtx(_orb, nctx, _env, makeFullName(path)); } catch (Exception e) { throw ExceptionMapper.mapException(e, this, path); } } /** * Uses the callBindNewContext convenience function to create a new * context. Throws an invalid name exception if the name is empty. * * @param name string * @return the new context object. * @throws NamingException See callBindNewContext */ public javax.naming.Context createSubcontext(String name) throws NamingException { return createSubcontext(new CompositeName(name)); } /** * Uses the callBindNewContext convenience function to create a new * context. Throws an invalid name exception if the name is empty. * * @param name string * @return the new context object. * @throws NamingException See callBindNewContext */ public javax.naming.Context createSubcontext(Name name) throws NamingException { if (name.size() == 0) throw IIOPLogger.ROOT_LOGGER.invalidEmptyName(); NameComponent[] path = CNNameParser.nameToCosName(name); try { return callBindNewContext(path); } catch (CannotProceedException e) { javax.naming.Context cctx = getContinuationContext(e); return cctx.createSubcontext(e.getRemainingName()); } } /** * Is mapped to resolve in the COS Naming api. * * @param name string * @return the resolved object. * @throws NamingException See lookup. */ public Object lookupLink(String name) throws NamingException { return lookupLink(new CompositeName(name)); } /** * Is mapped to resolve in the COS Naming api. * * @param name string * @return the resolved object. * @throws NamingException See lookup. */ public Object lookupLink(Name name) throws NamingException { return lookup(name); } /** * Allow access to the name parser object. * * @param name, is ignored since there is only one Name * Parser object. * @return NameParser object * @throws NamingException -- */ public NameParser getNameParser(String name) throws NamingException { return parser; } /** * Allow access to the name parser object. * * @param name JNDI name, is ignored since there is only one Name * Parser object. * @return NameParser object * @throws NamingException -- */ public NameParser getNameParser(Name name) throws NamingException { return parser; } /** * Returns the current environment. * * @return Environment. */ public Hashtable getEnvironment() throws NamingException { if (_env == null) { return new Hashtable(5, 0.75f); } else { return (Hashtable) _env.clone(); } } public String composeName(String name, String prefix) throws NamingException { return composeName(new CompositeName(name), new CompositeName(prefix)).toString(); } public Name composeName(Name name, Name prefix) throws NamingException { Name result = (Name) prefix.clone(); return result.addAll(name); } /** * Adds to the environment for the current context. * Record change but do not reinitialize ORB. * * @param propName The property name. * @param propValue The ORB. * @return the previous value of this property if any. */ public Object addToEnvironment(String propName, Object propValue) throws NamingException { if (_env == null) { _env = new Hashtable(7, 0.75f); } else { // copy-on-write _env = (Hashtable) _env.clone(); } return _env.put(propName, propValue); } // Record change but do not reinitialize ORB public Object removeFromEnvironment(String propName) throws NamingException { if (_env != null && _env.get(propName) != null) { // copy-on-write _env = (Hashtable) _env.clone(); return _env.remove(propName); } return null; } public synchronized void close() throws NamingException { } protected void finalize() { try { close(); } catch (NamingException e) { // ignore failures } } }
41,664
36.267442
118
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/IiopUrl.java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.net.MalformedURLException; import java.util.StringTokenizer; import java.util.Vector; import javax.naming.Name; import javax.naming.NamingException; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Extract components of an "iiop" or "iiopname" URL. * <p/> * The format of an iiopname URL is defined in INS 98-10-11 as follows: * <p/> * iiopname url = "iiopname://" [addr_list]["/" string_name] * addr_list = [address ","]* address * address = [version host [":" port]] * host = DNS style host name | IP address * version = major "." minor "@" | empty_string * port = number * major = number * minor = number * string_name = stringified name | empty_string * <p/> * The default port is 9999. The default version is "1.0" * US-ASCII alphanumeric characters are not escaped. Any characters outside * of this range are escaped except for the following: * ; / : ? : @ & = + $ , - _ . ! ~ * ' ( ) * Escaped characters is escaped by using a % followed by its 2 hexadecimal * numbers representing the octet. * <p/> * For backward compatibility, the "iiop" URL as defined in INS 97-6-6 * is also supported: * <p/> * iiop url = "iiop://" [host [":" port]] ["/" string_name] * The default port is 900. * * @author Rosanna Lee */ public final class IiopUrl { private static final int DEFAULT_IIOPNAME_PORT = 9999; private static final int DEFAULT_IIOP_PORT = 900; private static final String DEFAULT_HOST = "localhost"; private Vector addresses; private String stringName; public static class Address { public int port = -1; public int major, minor; public String host; public Address(String hostPortVers, boolean oldFormat) throws MalformedURLException { // [version host [":" port]] int start; // Parse version int at; if (oldFormat || (at = hostPortVers.indexOf('@')) < 0) { major = 1; minor = 0; start = 0; // start at the beginning } else { int dot = hostPortVers.indexOf('.'); if (dot < 0) { throw IIOPLogger.ROOT_LOGGER.invalidIIOPURLVersion(hostPortVers); } try { major = Integer.parseInt(hostPortVers.substring(0, dot)); minor = Integer.parseInt(hostPortVers.substring(dot + 1, at)); } catch (NumberFormatException e) { throw IIOPLogger.ROOT_LOGGER.invalidIIOPURLVersion(hostPortVers); } start = at + 1; // skip '@' sign } // Parse host and port int slash = hostPortVers.indexOf('/', start); if (slash < 0) { slash = hostPortVers.length(); } if (hostPortVers.startsWith("[", start)) { // at IPv6 literal int brac = hostPortVers.indexOf(']', start + 1); if (brac < 0 || brac > slash) { throw IIOPLogger.ROOT_LOGGER.invalidURL("iiopname", hostPortVers); } // include brackets host = hostPortVers.substring(start, brac + 1); start = brac + 1; } else { // at hostname or IPv4 int colon = hostPortVers.indexOf(':', start); int hostEnd = (colon < 0 || colon > slash) ? slash : colon; if (start < hostEnd) { host = hostPortVers.substring(start, hostEnd); } start = hostEnd; // skip past host } if ((start + 1 < slash)) { if (hostPortVers.startsWith(":", start)) { // parse port start++; // skip past ":" port = Integer.parseInt(hostPortVers. substring(start, slash)); } else { throw IIOPLogger.ROOT_LOGGER.invalidURL("iiopname", hostPortVers); } } start = slash; if ("".equals(host) || host == null) { host = DEFAULT_HOST; } if (port == -1) { port = (oldFormat ? DEFAULT_IIOP_PORT : DEFAULT_IIOPNAME_PORT); } } } public Vector getAddresses() { return addresses; } /** * Returns a possibly empty but non-null string that is the "string_name" * portion of the URL. */ public String getStringName() { return stringName; } public Name getCosName() throws NamingException { return CNCtx.parser.parse(stringName); } public IiopUrl(String url) throws MalformedURLException { int addrStart; boolean oldFormat; if (url.startsWith("iiopname://")) { oldFormat = false; addrStart = 11; } else if (url.startsWith("iiop://")) { oldFormat = true; addrStart = 7; } else { throw IIOPLogger.ROOT_LOGGER.invalidURL("iiop/iiopname", url); } int addrEnd = url.indexOf('/', addrStart); if (addrEnd < 0) { addrEnd = url.length(); stringName = ""; } else { stringName = UrlUtil.decode(url.substring(addrEnd + 1)); } addresses = new Vector(3); if (oldFormat) { // Only one host:port part, not multiple addresses.addElement( new Address(url.substring(addrStart, addrEnd), oldFormat)); } else { StringTokenizer tokens = new StringTokenizer(url.substring(addrStart, addrEnd), ","); while (tokens.hasMoreTokens()) { addresses.addElement(new Address(tokens.nextToken(), oldFormat)); } if (addresses.isEmpty()) { addresses.addElement(new Address("", oldFormat)); } } } }
7,407
35.673267
86
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CorbanameUrl.java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.net.MalformedURLException; import javax.naming.Name; import javax.naming.NamingException; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Extract components of a "corbaname" URL. * * The format of a corbaname URL is defined in INS 99-12-03 as follows. *<p> * corbaname url = "corbaname:" <corbaloc_obj> ["#" <string_name>] * corbaloc_obj = <obj_addr_list> ["/" <key_string>] * obj_addr_list = as defined in a corbaloc URL * key_string = as defined in a corbaloc URL * string_name = stringified COS name | empty_string *<p> * Characters in <string_name> are escaped as follows. * US-ASCII alphanumeric characters are not escaped. Any characters outside * of this range are escaped except for the following: * ; / : ? @ & = + $ , - _ . ! ~ * ; ( ) * Escaped characters is escaped by using a % followed by its 2 hexadecimal * numbers representing the octet. *<p> * The corbaname URL is parsed into two parts: a corbaloc URL and a COS name. * The corbaloc URL is constructed by concatenation "corbaloc:" with * <corbaloc_obj>. * The COS name is <string_name> with the escaped characters resolved. *<p> * A corbaname URL is resolved by: *<ol> *<li>Construct a corbaloc URL by concatenating "corbaloc:" and <corbaloc_obj>. *<li>Resolve the corbaloc URL to a NamingContext by using * nctx = ORB.string_to_object(corbalocUrl); *<li>Resolve <string_name> in the NamingContext. *</ol> * * @author Rosanna Lee */ public final class CorbanameUrl { private final String stringName; private final String location; /** * Returns a possibly empty but non-null string that is the "string_name" * portion of the URL. */ public String getStringName() { return stringName; } public Name getCosName() throws NamingException { return CNCtx.parser.parse(stringName); } public String getLocation() { return "corbaloc:" + location; } public CorbanameUrl(String url) throws MalformedURLException { if (!url.startsWith("corbaname:")) { throw IIOPLogger.ROOT_LOGGER.invalidURL("corbaname", url); } int addrStart = 10; // "corbaname:" int addrEnd = url.indexOf('#', addrStart); if (addrEnd < 0) { addrEnd = url.length(); stringName = ""; } else { stringName = UrlUtil.decode(url.substring(addrEnd+1)); } String location = url.substring(addrStart, addrEnd); int keyStart = location.indexOf("/"); if (keyStart >= 0) { // Has key string if (keyStart == (location.length() -1)) { location += "NameService"; } } else { location += "/NameService"; } this.location = location; } }
4,083
33.610169
79
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CNNameParser.java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import javax.naming.CompositeName; import javax.naming.CompoundName; import javax.naming.InvalidNameException; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; import org.omg.CosNaming.NameComponent; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Parsing routines for NameParser as well as COS Naming stringified names. * This is used by CNCtx to create a NameComponent[] object and vice versa. * It follows Section 4.5 of Interoperable Naming Service (INS) 98-10-11. * In summary, the stringified form is a left-to-right, forward-slash * separated name. id and kinds are separated by '.'. backslash is the * escape character. * * @author Rosanna Lee */ public final class CNNameParser implements NameParser { private static final Properties mySyntax = new Properties(); private static final char kindSeparator = '.'; private static final char compSeparator = '/'; private static final char escapeChar = '\\'; static { mySyntax.put("jndi.syntax.direction", "left_to_right"); mySyntax.put("jndi.syntax.separator", "" + compSeparator); mySyntax.put("jndi.syntax.escape", "" + escapeChar); } /** * Constructs a new name parser for parsing names in INS syntax. */ public CNNameParser() { } /** * Returns a CompoundName given a string in INS syntax. * * @param name The non-null string representation of the name. * @return a non-null CompoundName */ public Name parse(String name) throws NamingException { Vector comps = insStringToStringifiedComps(name); return new CNCompoundName(comps.elements()); } /** * Creates a NameComponent[] from a Name structure. * Used by CNCtx to convert the input Name arg into a NameComponent[]. * * @param name a CompoundName or a CompositeName; * each component must be the stringified form of a NameComponent. */ static NameComponent[] nameToCosName(Name name) throws InvalidNameException { int len = name.size(); if (len == 0) { return new NameComponent[0]; } NameComponent[] answer = new NameComponent[len]; for (int i = 0; i < len; i++) { answer[i] = parseComponent(name.get(i)); } return answer; } /** * Returns the INS stringified form of a NameComponent[]. * Used by CNCtx.getNameInNamespace(), CNCompoundName.toString(). */ static String cosNameToInsString(NameComponent[] cname) { StringBuffer str = new StringBuffer(); for (int i = 0; i < cname.length; i++) { if (i > 0) { str.append(compSeparator); } str.append(stringifyComponent(cname[i])); } return str.toString(); } /** * Creates a CompositeName from a NameComponent[]. * Used by ExceptionMapper and CNBindingEnumeration to convert * a NameComponent[] into a composite name. */ static Name cosNameToName(NameComponent[] cname) { Name nm = new CompositeName(); for (int i = 0; cname != null && i < cname.length; i++) { try { nm.add(stringifyComponent(cname[i])); } catch (InvalidNameException e) { // ignore } } return nm; } /** * Converts an INS-syntax string name into a Vector in which * each element of the vector contains a stringified form of * a NameComponent. */ private static Vector insStringToStringifiedComps(String str) throws InvalidNameException { int len = str.length(); Vector components = new Vector(10); char[] id = new char[len]; char[] kind = new char[len]; int idCount, kindCount; boolean idMode; for (int i = 0; i < len; ) { idCount = kindCount = 0; // reset for new component idMode = true; // always start off parsing id while (i < len) { if (str.charAt(i) == compSeparator) { break; } else if (str.charAt(i) == escapeChar) { if (i + 1 >= len) { throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(str); } else if (isMeta(str.charAt(i + 1))) { ++i; // skip escape and let meta through if (idMode) { id[idCount++] = str.charAt(i++); } else { kind[kindCount++] = str.charAt(i++); } } else { throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(str); } } else if (idMode && str.charAt(i) == kindSeparator) { // just look for the first kindSeparator ++i; // skip kind separator idMode = false; } else { if (idMode) { id[idCount++] = str.charAt(i++); } else { kind[kindCount++] = str.charAt(i++); } } } components.addElement(stringifyComponent( new NameComponent(new String(id, 0, idCount), new String(kind, 0, kindCount)))); if (i < len) { ++i; // skip separator } } return components; } /** * Return a NameComponent given its stringified form. */ private static NameComponent parseComponent(String compStr) throws InvalidNameException { NameComponent comp = new NameComponent(); int kindSep = -1; int len = compStr.length(); int j = 0; char[] newStr = new char[len]; boolean escaped = false; // Find the kind separator for (int i = 0; i < len && kindSep < 0; i++) { if (escaped) { newStr[j++] = compStr.charAt(i); escaped = false; } else if (compStr.charAt(i) == escapeChar) { if (i + 1 >= len) { throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(compStr); } else if (isMeta(compStr.charAt(i + 1))) { escaped = true; } else { throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(compStr); } } else if (compStr.charAt(i) == kindSeparator) { kindSep = i; } else { newStr[j++] = compStr.charAt(i); } } // Set id comp.id = new String(newStr, 0, j); // Set kind if (kindSep < 0) { comp.kind = ""; // no kind separator } else { // unescape kind j = 0; escaped = false; for (int i = kindSep + 1; i < len; i++) { if (escaped) { newStr[j++] = compStr.charAt(i); escaped = false; } else if (compStr.charAt(i) == escapeChar) { if (i + 1 >= len) { throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(compStr); } else if (isMeta(compStr.charAt(i + 1))) { escaped = true; } else { throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(compStr); } } else { newStr[j++] = compStr.charAt(i); } } comp.kind = new String(newStr, 0, j); } return comp; } private static String stringifyComponent(NameComponent comp) { StringBuffer one = new StringBuffer(escape(comp.id)); if (comp.kind != null && !comp.kind.equals("")) { one.append(kindSeparator + escape(comp.kind)); } if (one.length() == 0) { return "" + kindSeparator; // if neither id nor kind specified } else { return one.toString(); } } /** * Returns a string with '.', '\', '/' escaped. Used when * stringifying the name into its INS stringified form. */ private static String escape(String str) { if (str.indexOf(kindSeparator) < 0 && str.indexOf(compSeparator) < 0 && str.indexOf(escapeChar) < 0) { return str; // no meta characters to escape } else { int len = str.length(); int j = 0; char[] newStr = new char[len + len]; for (int i = 0; i < len; i++) { if (isMeta(str.charAt(i))) { newStr[j++] = escapeChar; // escape meta character } newStr[j++] = str.charAt(i); } return new String(newStr, 0, j); } } /** * In INS, there are three meta characters: '.', '/' and '\'. */ private static boolean isMeta(char ch) { switch (ch) { case kindSeparator: case compSeparator: case escapeChar: return true; } return false; } /** * An implementation of CompoundName that bypasses the parsing * and stringifying code of the default CompoundName. */ static final class CNCompoundName extends CompoundName { CNCompoundName(Enumeration enum_) { super(enum_, CNNameParser.mySyntax); } public Object clone() { return new CNCompoundName(getAll()); } public Name getPrefix(int posn) { Enumeration comps = super.getPrefix(posn).getAll(); return new CNCompoundName(comps); } public Name getSuffix(int posn) { Enumeration comps = super.getSuffix(posn).getAll(); return new CNCompoundName(comps); } public String toString() { try { // Convert Name to NameComponent[] then stringify return cosNameToInsString(nameToCosName(this)); } catch (InvalidNameException e) { return super.toString(); } } private static final long serialVersionUID = -6599252802678482317L; } }
11,859
33.577259
86
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CNCtxFactory.java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; /** * Implements the JNDI SPI InitialContextFactory interface used to * create the InitialContext objects. * * @author Raj Krishnamurthy */ public class CNCtxFactory implements InitialContextFactory { public static final CNCtxFactory INSTANCE = new CNCtxFactory(); /** * Creates the InitialContext object. Properties parameter should * should contain the ORB object for the value jndi.corba.orb. * * @param env Properties object */ public Context getInitialContext(Hashtable<?, ?> env) throws NamingException { return new CNCtx(env); } }
2,001
34.75
82
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/RemoteToCorba.java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.rmi.Remote; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.spi.StateFactory; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * StateFactory that turns java.rmi.Remote objects to org.omg.CORBA.Object. * * @author Rosanna Lee */ public class RemoteToCorba implements StateFactory { public RemoteToCorba() { } /** * Returns the CORBA object for a Remote object. * If input is not a Remote object, or if Remote object uses JRMP, return null. * If the RMI-IIOP library is not available, throw ConfigurationException. * * @param orig The object to turn into a CORBA object. If not Remote, * or if is a JRMP stub or impl, return null. * @param name Ignored * @param ctx The non-null CNCtx whose ORB to use. * @param env Ignored * @return The CORBA object for <tt>orig</tt> or null. * @throws javax.naming.ConfigurationException If the CORBA object cannot be obtained * due to configuration problems, for instance, if RMI-IIOP not available. * @throws NamingException If some other problem prevented a CORBA * object from being obtained from the Remote object. */ public Object getStateToBind(Object orig, Name name, Context ctx, Hashtable<?, ?> env) throws NamingException { if (orig instanceof org.omg.CORBA.Object) { // Already a CORBA object, just use it return null; } if (orig instanceof Remote) { // Turn remote object into org.omg.CORBA.Object try { // Returns null if JRMP; let next factory try // CNCtx will eventually throw IllegalArgumentException if // no CORBA object gotten return CorbaUtils.remoteToCorba((Remote) orig, ((CNCtx) ctx)._orb); } catch (ClassNotFoundException e) { // RMI-IIOP library not available throw IIOPLogger.ROOT_LOGGER.unavailableRMIPackages(); } } return null; // pass and let next state factory try } }
3,563
39.5
109
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CorbaUtils.java
/* * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; // Needed for RMI/IIOP import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.rmi.Remote; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; import javax.naming.ConfigurationException; import javax.naming.Context; import org.omg.CORBA.ORB; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Contains utilities for performing CORBA-related tasks: * 1. Get the org.omg.CORBA.Object for a java.rmi.Remote object. * 2. Create an ORB to use for a given host/port, and environment properties. * * @author Simon Nash * @author Bryan Atsatt */ public class CorbaUtils { private static volatile Properties orbProperties; /** * Returns the CORBA object reference associated with a Remote * object by using the javax.rmi.CORBA package. * <p/> * Use reflection to avoid hard dependencies on javax.rmi.CORBA package. * This method effective does the following: * <blockquote><pre> * java.lang.Object stub; * try { * stub = PortableRemoteObject.toStub(remoteObj); * } catch (Exception e) { * throw new ConfigurationException("Object not exported or not found"); * } * if (!(stub instanceof javax.rmi.CORBA.Stub)) { * return null; // JRMP impl or JRMP stub * } * try { * ((javax.rmi.CORBA.Stub)stub).connect(orb); // try to connect IIOP stub * } catch (RemoteException e) { * // ignore 'already connected' error * } * return (javax.rmi.CORBA.Stub)stub; * * @param remoteObj The non-null remote object for * @param orb The non-null ORB to connect the remote object to * @return The CORBA Object for remoteObj; null if <tt>remoteObj</tt> * is a JRMP implementation or JRMP stub. * @throws ClassNotFoundException The RMI-IIOP package is not available * @throws ConfigurationException The CORBA Object cannot be obtained * because of configuration problems. */ public static org.omg.CORBA.Object remoteToCorba(Remote remoteObj, ORB orb) throws ClassNotFoundException, ConfigurationException { synchronized (CorbaUtils.class) { if (toStubMethod == null) { initMethodHandles(); } } // First, get remoteObj's stub // javax.rmi.CORBA.Stub stub = PortableRemoteObject.toStub(remoteObj); Object stub; try { stub = toStubMethod.invoke(null, new Object[]{remoteObj}); } catch (InvocationTargetException e) { Throwable realException = e.getTargetException(); // realException.printStackTrace(); ConfigurationException ce = IIOPLogger.ROOT_LOGGER.problemInvokingPortableRemoteObjectToStub(); ce.setRootCause(realException); throw ce; } catch (IllegalAccessException e) { ConfigurationException ce = IIOPLogger.ROOT_LOGGER.cannotInvokePortableRemoteObjectToStub(); ce.setRootCause(e); throw ce; } // Next, make sure that the stub is javax.rmi.CORBA.Stub if (!corbaStubClass.isInstance(stub)) { return null; // JRMP implementation or JRMP stub } // Next, make sure that the stub is connected // Invoke stub.connect(orb) try { connectMethod.invoke(stub, new Object[]{orb}); } catch (InvocationTargetException e) { Throwable realException = e.getTargetException(); // realException.printStackTrace(); if (!(realException instanceof java.rmi.RemoteException)) { ConfigurationException ce = IIOPLogger.ROOT_LOGGER.problemInvokingStubConnect(); ce.setRootCause(realException); throw ce; } // ignore RemoteException because stub might have already // been connected } catch (IllegalAccessException e) { ConfigurationException ce = IIOPLogger.ROOT_LOGGER.cannotInvokeStubConnect(); ce.setRootCause(e); throw ce; } // Finally, return stub return (org.omg.CORBA.Object) stub; } /** * Get ORB using given server and port number, and properties from environment. * * @param server Possibly null server; if null means use default; * For applet, it is the applet host; for app, it is localhost. * @param port Port number, -1 means default port * @param env Possibly null environment. Contains environment properties. * Could contain ORB itself; or applet used for initializing ORB. * Use all String properties from env for initializing ORB * @return A non-null ORB. */ public static ORB getOrb(String server, int port, Hashtable env) { // See if we can get info from environment Properties orbProp; // Extract any org.omg.CORBA properties from environment if (env != null) { // Get all String properties orbProp = new Properties(); final Enumeration envProp = env.keys(); while (envProp.hasMoreElements()) { String key = (String) envProp.nextElement(); Object val = env.get(key); if (val instanceof String) { orbProp.put(key, val); } } final Enumeration mainProps = orbProperties.keys(); while (mainProps.hasMoreElements()) { String key = (String) mainProps.nextElement(); Object val = orbProperties.get(key); if (val instanceof String) { orbProp.put(key, val); } } } else { orbProp = orbProperties; } if (server != null) { orbProp.put("org.omg.CORBA.ORBInitialHost", server); } if (port >= 0) { orbProp.put("org.omg.CORBA.ORBInitialPort", "" + port); } // Get Applet from environment if (env != null) { Object applet = env.get(Context.APPLET); if (applet != null) { // Create ORBs for an applet return initAppletORB(applet, orbProp); } } // Create ORBs using orbProp for a standalone application return ORB.init(new String[0], orbProp); } /** * This method returns a new ORB instance for the given applet * without creating a static dependency on java.applet. */ private static ORB initAppletORB(Object applet, Properties orbProp) { try { Class<?> appletClass = Class.forName("java.applet.Applet", true, null); if (!appletClass.isInstance(applet)) { throw new ClassCastException(applet.getClass().getName()); } // invoke the static method ORB.init(applet, orbProp); Method method = ORB.class.getMethod("init", appletClass, Properties.class); return (ORB) method.invoke(null, applet, orbProp); } catch (ClassNotFoundException e) { // java.applet.Applet doesn't exist and the applet parameter is // non-null; so throw CCE throw new ClassCastException(applet.getClass().getName()); } catch (NoSuchMethodException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw new AssertionError(e); } catch (IllegalAccessException iae) { throw new AssertionError(iae); } } // Fields used for reflection of RMI-IIOP private static Method toStubMethod = null; private static Method connectMethod = null; private static Class corbaStubClass = null; /** * Initializes reflection method handles for RMI-IIOP. * * @throws ClassNotFoundException javax.rmi.CORBA.* not available */ private static void initMethodHandles() throws ClassNotFoundException { // Get javax.rmi.CORBA.Stub class corbaStubClass = Class.forName("javax.rmi.CORBA.Stub"); // Get javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB) method try { connectMethod = corbaStubClass.getMethod("connect", new Class[]{ORB.class}); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noMethodDefForStubConnect(); } // Get javax.rmi.PortableRemoteObject method Class proClass = Class.forName("javax.rmi.PortableRemoteObject"); // Get javax.rmi.PortableRemoteObject(java.rmi.Remote) method try { toStubMethod = proClass.getMethod("toStub", new Class[]{Remote.class}); } catch (NoSuchMethodException e) { throw IIOPLogger.ROOT_LOGGER.noMethodDefForPortableRemoteObjectToStub(); } } public static Properties getOrbProperties() { return orbProperties; } public static void setOrbProperties(final Properties orbProperties) { CorbaUtils.orbProperties = orbProperties; } }
10,687
36.900709
107
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/CNBindingEnumeration.java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.util.Hashtable; import java.util.NoSuchElementException; import javax.naming.Name; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import org.omg.CosNaming.BindingIterator; import org.omg.CosNaming.BindingIteratorHolder; import org.omg.CosNaming.BindingListHolder; import org.omg.CosNaming.NameComponent; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Implements the JNDI NamingEnumeration interface for COS * Naming. Gets hold of a list of bindings from the COS Naming Server * and allows the client to iterate through them. * * @author Raj Krishnamurthy * @author Rosanna Lee */ final class CNBindingEnumeration implements NamingEnumeration { private static final int DEFAULT_BATCHSIZE = 100; private BindingListHolder _bindingList; // list of bindings private BindingIterator _bindingIter; // iterator for getting list of bindings private int counter; // pointer in _bindingList private int batchsize = DEFAULT_BATCHSIZE; // how many to ask for each time private CNCtx _ctx; // ctx to list private Hashtable _env; // environment for getObjectInstance private boolean more = false; // iterator done? private boolean isLookedUpCtx = false; // iterating on a context beneath this context ? /** * Creates a CNBindingEnumeration object. * * @param ctx Context to enumerate */ CNBindingEnumeration(CNCtx ctx, boolean isLookedUpCtx, Hashtable env) { // Get batch size to use String batch = (env != null ? (String) env.get(javax.naming.Context.BATCHSIZE) : null); if (batch != null) { try { batchsize = Integer.parseInt(batch); } catch (NumberFormatException e) { throw IIOPLogger.ROOT_LOGGER.illegalBatchSize(batch); } } _ctx = ctx; this.isLookedUpCtx = isLookedUpCtx; _env = env; _bindingList = new BindingListHolder(); BindingIteratorHolder _bindingIterH = new BindingIteratorHolder(); // Perform listing and request that bindings be returned in _bindingIter // Upon return,_bindingList returns a zero length list _ctx._nc.list(0, _bindingList, _bindingIterH); _bindingIter = _bindingIterH.value; // Get first batch using _bindingIter if (_bindingIter != null) { more = _bindingIter.next_n(batchsize, _bindingList); } else { more = false; } counter = 0; } /** * Returns the next binding in the list. * * @throws NamingException any naming exception. */ public Object next() throws NamingException { if (more && counter >= _bindingList.value.length) { getMore(); } if (more && counter < _bindingList.value.length) { org.omg.CosNaming.Binding bndg = _bindingList.value[counter]; counter++; return mapBinding(bndg); } else { throw new NoSuchElementException(); } } /** * Returns true or false depending on whether there are more bindings. * * @return boolean value */ public boolean hasMore() throws NamingException { // If there's more, check whether current bindingList has been exhausted, // and if so, try to get more. // If no more, just say so. return more ? (counter < _bindingList.value.length || getMore()) : false; } /** * Returns true or false depending on whether there are more bindings. * Need to define this to satisfy the Enumeration api requirement. * * @return boolean value */ public boolean hasMoreElements() { try { return hasMore(); } catch (NamingException e) { return false; } } /** * Returns the next binding in the list. * * @throws NoSuchElementException Thrown when the end of the * list is reached. */ public Object nextElement() { try { return next(); } catch (NamingException ne) { throw new NoSuchElementException(); } } public void close() throws NamingException { more = false; if (_bindingIter != null) { _bindingIter.destroy(); _bindingIter = null; } if (_ctx != null) { /** * context was obtained by CNCtx, the user doesn't have a handle to * it, close it as we are done enumerating through the context */ if (isLookedUpCtx) { _ctx.close(); } _ctx = null; } } protected void finalize() { try { close(); } catch (NamingException e) { // ignore failures } } /** * Get the next batch using _bindingIter. Update the 'more' field. */ private boolean getMore() throws NamingException { try { more = _bindingIter.next_n(batchsize, _bindingList); counter = 0; // reset } catch (Exception e) { more = false; NamingException ne = IIOPLogger.ROOT_LOGGER.errorGettingBindingList(); ne.setRootCause(e); throw ne; } return more; } /** * Constructs a JNDI Binding object from the COS Naming binding * object. * * @throws org.omg.CosNaming.NamingContextPackage.CannotProceed Unable to obtain a continuation context * @throws org.omg.CosNaming.NamingContextPackage.InvalidNameCNCtx Name not understood. * @throws NamingException One of the above. */ private javax.naming.Binding mapBinding(org.omg.CosNaming.Binding bndg) throws NamingException { Object obj = _ctx.callResolve(bndg.binding_name); Name cname = CNNameParser.cosNameToName(bndg.binding_name); try { obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env); } catch (NamingException e) { throw e; } catch (Exception e) { NamingException ne = IIOPLogger.ROOT_LOGGER.errorGeneratingObjectViaFactory(); ne.setRootCause(e); throw ne; } // Use cname.toString() instead of bindingName because the name // in the binding should be a composite name String cnameStr = cname.toString(); javax.naming.Binding jbndg = new javax.naming.Binding(cnameStr, obj); NameComponent[] comps = _ctx.makeFullName(bndg.binding_name); String fullName = CNNameParser.cosNameToInsString(comps); jbndg.setNameInNamespace(fullName); return jbndg; } }
8,154
32.838174
109
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/UrlUtil.java
/* * Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.net.MalformedURLException; import java.io.UnsupportedEncodingException; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Utilities for dealing with URLs. * * @author Vincent Ryan */ public final class UrlUtil { // To prevent creation of this static class private UrlUtil() { } /** * Decode a URI string (according to RFC 2396). */ public static String decode(String s) throws MalformedURLException { try { return decode(s, "8859_1"); } catch (UnsupportedEncodingException e) { // ISO-Latin-1 should always be available? throw IIOPLogger.ROOT_LOGGER.unavailableISOLatin1Decoder(); } } /** * Decode a URI string (according to RFC 2396). * <p/> * Three-character sequences '%xy', where 'xy' is the two-digit * hexadecimal representation of the lower 8-bits of a character, * are decoded into the character itself. * <p/> * The string is subsequently converted using the specified encoding */ public static String decode(String s, String enc) throws MalformedURLException, UnsupportedEncodingException { int length = s.length(); byte[] bytes = new byte[length]; int j = 0; for (int i = 0; i < length; i++) { if (s.charAt(i) == '%') { i++; // skip % try { bytes[j++] = (byte) Integer.parseInt(s.substring(i, i + 2), 16); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.invalidURIEncoding(s); } i++; // skip first hex char; for loop will skip second one } else { bytes[j++] = (byte) s.charAt(i); } } return new String(bytes, 0, j, enc); } /** * Encode a string for inclusion in a URI (according to RFC 2396). * <p/> * Unsafe characters are escaped by encoding them in three-character * sequences '%xy', where 'xy' is the two-digit hexadecimal representation * of the lower 8-bits of the character. * <p/> * The question mark '?' character is also escaped, as required by RFC 2255. * <p/> * The string is first converted to the specified encoding. * For LDAP (2255), the encoding must be UTF-8. */ public static String encode(String s, String enc) throws UnsupportedEncodingException { byte[] bytes = s.getBytes(enc); int count = bytes.length; /* * From RFC 2396: * * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" * reserved = ";" | "/" | ":" | "?" | "@" | "&" | "=" | "+" | "$" | "," */ final String allowed = "=,+;.'-@&/$_()!~*:"; // '?' is omitted char[] buf = new char[3 * count]; int j = 0; for (int i = 0; i < count; i++) { if ((bytes[i] >= 0x61 && bytes[i] <= 0x7A) || // a..z (bytes[i] >= 0x41 && bytes[i] <= 0x5A) || // A..Z (bytes[i] >= 0x30 && bytes[i] <= 0x39) || // 0..9 (allowed.indexOf(bytes[i]) >= 0)) { buf[j++] = (char) bytes[i]; } else { buf[j++] = '%'; buf[j++] = Character.forDigit(0xF & (bytes[i] >>> 4), 16); buf[j++] = Character.forDigit(0xF & bytes[i], 16); } } return new String(buf, 0, j); } }
4,800
34.562963
80
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/JBossCNCtxFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.naming.jndi; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.spi.ObjectFactory; /** * Adaptor that allows cosnaming to work inside the AS. * * @author Stuart Douglas */ public class JBossCNCtxFactory implements ObjectFactory { public static final JBossCNCtxFactory INSTANCE = new JBossCNCtxFactory(); private JBossCNCtxFactory() { } @Override public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable environment) throws Exception { return new WrapperInitialContext(environment); } }
1,688
32.78
141
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/naming/jndi/ExceptionMapper.java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.wildfly.iiop.openjdk.naming.jndi; import javax.naming.CannotProceedException; import javax.naming.CompositeName; import javax.naming.ContextNotEmptyException; import javax.naming.InvalidNameException; import javax.naming.Name; import javax.naming.NameAlreadyBoundException; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.spi.NamingManager; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextPackage.AlreadyBound; import org.omg.CosNaming.NamingContextPackage.CannotProceed; import org.omg.CosNaming.NamingContextPackage.InvalidName; import org.omg.CosNaming.NamingContextPackage.NotEmpty; import org.omg.CosNaming.NamingContextPackage.NotFound; import org.omg.CosNaming.NamingContextPackage.NotFoundReason; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * A convenience class to map the COS Naming exceptions to the JNDI exceptions. * * @author Raj Krishnamurthy */ public final class ExceptionMapper { private ExceptionMapper() { } // ensure no instance private static final boolean debug = false; public static NamingException mapException(Exception e, CNCtx ctx, NameComponent[] inputName) throws NamingException { if (e instanceof NamingException) { return (NamingException) e; } if (e instanceof RuntimeException) { throw (RuntimeException) e; } NamingException ne; if (e instanceof NotFound) { if (ctx.federation) { return tryFed((NotFound) e, ctx, inputName); } else { ne = new NameNotFoundException(); } } else if (e instanceof CannotProceed) { ne = new CannotProceedException(); NamingContext nc = ((CannotProceed) e).cxt; NameComponent[] rest = ((CannotProceed) e).rest_of_name; // %%% We assume that rest returns *all* unprocessed components. // Don't' know if that is a good assumption, given // NotFound doesn't set rest as expected. -RL if (inputName != null && (inputName.length > rest.length)) { NameComponent[] resolvedName = new NameComponent[inputName.length - rest.length]; System.arraycopy(inputName, 0, resolvedName, 0, resolvedName.length); // Wrap resolved NamingContext inside a CNCtx // Guess that its name (which is relative to ctx) // is the part of inputName minus rest_of_name ne.setResolvedObj(new CNCtx(ctx._orb, nc, ctx._env, ctx.makeFullName(resolvedName))); } else { ne.setResolvedObj(ctx); } ne.setRemainingName(CNNameParser.cosNameToName(rest)); } else if (e instanceof InvalidName) { ne = new InvalidNameException(); } else if (e instanceof AlreadyBound) { ne = new NameAlreadyBoundException(); } else if (e instanceof NotEmpty) { ne = new ContextNotEmptyException(); } else { ne = new NamingException(); } ne.setRootCause(e); return ne; } private static NamingException tryFed(NotFound e, CNCtx ctx, NameComponent[] inputName) throws NamingException { NameComponent[] rest = ((NotFound) e).rest_of_name; if (debug) { } // %%% Using 1.2 & 1.3 Sun's tnameserv, 'rest' contains only the first // component that failed, not *rest* as advertized. This is useless // because what if you have something like aa/aa/aa/aa/aa. // If one of those is not found, you get "aa" as 'rest'. if (rest.length == 1 && inputName != null) { // Check that we're not talking to 1.2/1.3 Sun tnameserv NameComponent lastIn = inputName[inputName.length - 1]; if (rest[0].id.equals(lastIn.id) && rest[0].kind != null && rest[0].kind.equals(lastIn.kind)) { // Might be legit } else { // Due to 1.2/1.3 bug that always returns single-item 'rest' NamingException ne = new NameNotFoundException(); ne.setRemainingName(CNNameParser.cosNameToName(rest)); ne.setRootCause(e); throw ne; } } // Fixed in 1.4; perform calculations based on correct (1.4) behavior // Calculate the components of the name that has been resolved NameComponent[] resolvedName = null; int len = 0; if (inputName != null && (inputName.length >= rest.length)) { if (e.why == NotFoundReason.not_context) { // First component of rest is found but not a context; keep it // as part of resolved name len = inputName.length - (rest.length - 1); // Remove resolved component from rest if (rest.length == 1) { // No more remaining rest = null; } else { NameComponent[] tmp = new NameComponent[rest.length - 1]; System.arraycopy(rest, 1, tmp, 0, tmp.length); rest = tmp; } } else { len = inputName.length - rest.length; } if (len > 0) { resolvedName = new NameComponent[len]; System.arraycopy(inputName, 0, resolvedName, 0, len); } } // Create CPE and set common fields CannotProceedException cpe = new CannotProceedException(); cpe.setRootCause(e); if (rest != null && rest.length > 0) { cpe.setRemainingName(CNNameParser.cosNameToName(rest)); } cpe.setEnvironment(ctx._env); // Lookup resolved name to get resolved object final Object resolvedObj = (resolvedName != null) ? ctx.callResolve(resolvedName) : ctx; if (resolvedObj instanceof javax.naming.Context) { // obj is a context and child is not found // try getting its nns dynamically by constructing // a Reference containing obj. RefAddr addr = new RefAddr("nns") { public Object getContent() { return resolvedObj; } private static final long serialVersionUID = 669984699392133792L; }; Reference ref = new Reference("java.lang.Object", addr); // Resolved name has trailing slash to indicate nns CompositeName cname = new CompositeName(); cname.add(""); // add trailing slash cpe.setResolvedObj(ref); cpe.setAltName(cname); cpe.setAltNameCtx((javax.naming.Context) resolvedObj); return cpe; } else { // Not a context, use object factory to transform object. Name cname = CNNameParser.cosNameToName(resolvedName); Object resolvedObj2; try { resolvedObj2 = NamingManager.getObjectInstance(resolvedObj, cname, ctx, ctx._env); } catch (NamingException ge) { throw ge; } catch (Exception ge) { NamingException ne = IIOPLogger.ROOT_LOGGER.errorGeneratingObjectViaFactory(); ne.setRootCause(ge); throw ne; } // If a context, continue operation with context if (resolvedObj2 instanceof javax.naming.Context) { cpe.setResolvedObj(resolvedObj2); } else { // Add trailing slash cname.add(""); cpe.setAltName(cname); // Create nns reference final Object rf2 = resolvedObj2; RefAddr addr = new RefAddr("nns") { public Object getContent() { return rf2; } private static final long serialVersionUID = -785132553978269772L; }; Reference ref = new Reference("java.lang.Object", addr); cpe.setResolvedObj(ref); cpe.setAltNameCtx(ctx); } return cpe; } } }
9,836
38.191235
122
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/SASTargetInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.CSI.CompleteEstablishContext; import org.omg.CSI.ContextError; import org.omg.CSI.EstablishContext; import org.omg.CSI.GSS_NT_ExportedNameHelper; import org.omg.CSI.ITTPrincipalName; import org.omg.CSI.IdentityToken; import org.omg.CSI.MTEstablishContext; import org.omg.CSI.MTMessageInContext; import org.omg.CSI.SASContextBody; import org.omg.CSI.SASContextBodyHelper; import org.omg.GSSUP.ErrorToken; import org.omg.GSSUP.ErrorTokenHelper; import org.omg.GSSUP.GSS_UP_S_G_UNSPECIFIED; import org.omg.GSSUP.InitialContextToken; import org.omg.IOP.Codec; import org.omg.IOP.ServiceContext; import org.omg.IOP.CodecPackage.FormatMismatch; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.IOP.CodecPackage.TypeMismatch; import org.omg.PortableInterceptor.ServerRequestInfo; import org.omg.PortableInterceptor.ServerRequestInterceptor; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.service.CorbaORBService; /** * <p> * This implementation of {@code org.omg.PortableInterceptor.ServerRequestInterceptor} extracts the security attribute * service (SAS) context from incoming IIOP and inserts SAS messages into the SAS context of outgoing IIOP replies. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class SASTargetInterceptor extends LocalObject implements ServerRequestInterceptor { private static final long serialVersionUID = -4809929027984284871L; private static final int sasContextId = org.omg.IOP.SecurityAttributeService.value; private static final byte[] empty = new byte[0]; private static final IdentityToken absent; /** * scratch field for {@code CompleteEstablishContext} messages */ private static final SASContextBody msgBodyCtxAccepted; /** * Ready-to-go {@code CompleteEstablishContext} message with context id set to zero */ private static final Any msgCtx0Accepted; static { // initialize absent. absent = new IdentityToken(); absent.absent(true); // initialize msgBodyCtxAccepted (Note that "context stateful" is always set to false. Even if the // client wants a stateful context, we negotiate the context down to stateless). CompleteEstablishContext ctxAccepted = new CompleteEstablishContext(0, /* context id */ false, /* context stateful */ new byte[0] /* no final token */); msgBodyCtxAccepted = new SASContextBody(); msgBodyCtxAccepted.complete_msg(ctxAccepted); // initialize msgCtx0Accepted. msgCtx0Accepted = createMsgCtxAccepted(0); } private static Any createMsgCtxAccepted(long contextId) { Any any = ORB.init().create_any(); synchronized (msgBodyCtxAccepted) { msgBodyCtxAccepted.complete_msg().client_context_id = contextId; SASContextBodyHelper.insert(any, msgBodyCtxAccepted); } return any; } private final Codec codec; /** * scratch field for {@code ContextError} messages */ private final SASContextBody msgBodyCtxError; /** * ready-to-go {@code ContextError} message with context id set to zero and major status "invalid evidence" */ private final Any msgCtx0Rejected; private ThreadLocal<CurrentRequestInfo> threadLocalData = new ThreadLocal<CurrentRequestInfo>() { protected synchronized CurrentRequestInfo initialValue() { return new CurrentRequestInfo(); // see nested class below } }; /** * The {@code CurrentRequestInfo} class holds SAS information associated with IIOP request handled by the current thread. */ private static class CurrentRequestInfo { boolean sasContextReceived; boolean authenticationTokenReceived; byte[] incomingUsername; byte[] incomingPassword; byte[] incomingTargetName; IdentityToken incomingIdentity; byte[] incomingPrincipalName; long contextId; Any sasReply; boolean sasReplyIsAccept; /** * <p> * Creates an instance of {@code CurrentRequestInfo}. * </p> */ CurrentRequestInfo() { } } private Any createMsgCtxError(long contextId, int majorStatus) { Any any = ORB.init().create_any(); synchronized (msgBodyCtxError) { msgBodyCtxError.error_msg().client_context_id = contextId; msgBodyCtxError.error_msg().major_status = majorStatus; SASContextBodyHelper.insert(any, msgBodyCtxError); } return any; } /** * <p> * Creates an instance of {@code SASTargetInterceptor} with the specified codec. * </p> * * @param codec the {@code Codec} used to encode and decode the SAS components. */ public SASTargetInterceptor(Codec codec) { this.codec = codec; // build encapsulated GSSUP error token for ContextError messages (the error code within the error token is // GSS_UP_S_G_UNSPECIFIED, which says nothing about the cause of the error). ErrorToken errorToken = new ErrorToken(GSS_UP_S_G_UNSPECIFIED.value); Any any = ORB.init().create_any(); byte[] encapsulatedErrorToken; ErrorTokenHelper.insert(any, errorToken); try { encapsulatedErrorToken = codec.encode_value(any); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } // initialize msgBodyCtxError. ContextError ctxError = new ContextError(0, /* context id */ 1, /* major status: invalid evidence */ 1, /* minor status (always 1) */ encapsulatedErrorToken); msgBodyCtxError = new SASContextBody(); msgBodyCtxError.error_msg(ctxError); // initialize msgCtx0Rejected (major status: invalid evidence). msgCtx0Rejected = createMsgCtxError(0, 1); } /** * <p> * Indicates whether an SAS context has arrived with the current request or not. * </p> * * @return {@code true} if an SAS context arrived with the current IIOP request; {@code false} otherwise. */ boolean sasContextReceived() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.sasContextReceived; } /** * <p> * Indicates whether a client authentication token has arrived with the current request or not. * </p> * * @return {@code true} if a client authentication token arrived with the current IIOP request; {@code false} * otherwise. */ boolean authenticationTokenReceived() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.authenticationTokenReceived; } /** * <p> * Obtains the username that arrived with the current request. * </p> * * @return the username that arrived in the current IIOP request. */ byte[] getIncomingUsername() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.incomingUsername; } /** * <p> * Obtains the password that arrived in the current request. * </p> * * @return the password that arrived in the current IIOP request. */ byte[] getIncomingPassword() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.incomingPassword; } /** * <p> * Obtains the target name that arrived in the current request. * </p> * * @return the target name that arrived in the current IIOP request. */ byte[] getIncomingTargetName() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.incomingTargetName; } /** * <p> * Obtains the {@code org.omg.CSI.IdentityToken} that arrived in the current request. * </p> * * @return the {@code IdentityToken} that arrived in the current IIOP request. */ IdentityToken getIncomingIdentity() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.incomingIdentity; } /** * <p> * Obtains the principal name that arrived in the current request. * </p> * * @return the principal name that arrived in the current IIOP request. */ byte[] getIncomingPrincipalName() { CurrentRequestInfo threadLocal = threadLocalData.get(); return threadLocal.incomingPrincipalName; } /** * <p> * Sets the outgoing SAS reply to <code>ContextError</code>, with major status "invalid evidence". * </p> */ void rejectIncomingContext() { CurrentRequestInfo threadLocal = threadLocalData.get(); if (threadLocal.sasContextReceived) { threadLocal.sasReply = (threadLocal.contextId == 0) ? msgCtx0Rejected : createMsgCtxError(threadLocal.contextId, 1 /* major status: invalid evidence */); threadLocal.sasReplyIsAccept = false; } } @Override public String name() { return "SASTargetInterceptor"; } @Override public void destroy() { } @Override public void receive_request_service_contexts(ServerRequestInfo ri) { } @Override public void receive_request(ServerRequestInfo ri) { IIOPLogger.ROOT_LOGGER.tracef("receive_request: %s", ri.operation()); CurrentRequestInfo threadLocal = threadLocalData.get(); threadLocal.sasContextReceived = false; threadLocal.authenticationTokenReceived = false; threadLocal.incomingUsername = empty; threadLocal.incomingPassword = empty; threadLocal.incomingTargetName = empty; threadLocal.incomingIdentity = absent; threadLocal.incomingPrincipalName = empty; threadLocal.sasReply = null; threadLocal.sasReplyIsAccept = false; try { ServiceContext sc = ri.get_request_service_context(sasContextId); Any any = codec.decode_value(sc.context_data, SASContextBodyHelper.type()); SASContextBody contextBody = SASContextBodyHelper.extract(any); if (contextBody != null) { if (contextBody.discriminator() == MTMessageInContext.value) { // should not happen, as stateful context requests are always negotiated down to stateless in this implementation. long contextId = contextBody.in_context_msg().client_context_id; threadLocal.sasReply = createMsgCtxError(contextId, 4 /* major status: no context */); throw IIOPLogger.ROOT_LOGGER.missingSASContext(); } else if (contextBody.discriminator() == MTEstablishContext.value) { EstablishContext message = contextBody.establish_msg(); threadLocal.contextId = message.client_context_id; threadLocal.sasContextReceived = true; if (message.client_authentication_token != null && message.client_authentication_token.length > 0) { IIOPLogger.ROOT_LOGGER.trace("Received client authentication token"); InitialContextToken authToken = CSIv2Util.decodeInitialContextToken( message.client_authentication_token, codec); if (authToken == null) { threadLocal.sasReply = createMsgCtxError(message.client_context_id, 2 /* major status: invalid mechanism */); throw IIOPLogger.ROOT_LOGGER.errorDecodingInitContextToken(); } threadLocal.incomingUsername = authToken.username; threadLocal.incomingPassword = authToken.password; threadLocal.incomingTargetName = CSIv2Util.decodeGssExportedName(authToken.target_name); if (threadLocal.incomingTargetName == null) { threadLocal.sasReply = createMsgCtxError(message.client_context_id, 2 /* major status: invalid mechanism */); throw IIOPLogger.ROOT_LOGGER.errorDecodingTargetInContextToken(); } threadLocal.authenticationTokenReceived = true; } if (message.identity_token != null) { IIOPLogger.ROOT_LOGGER.trace("Received identity token"); threadLocal.incomingIdentity = message.identity_token; if (message.identity_token.discriminator() == ITTPrincipalName.value) { // Extract the RFC2743-encoded name from CDR encapsulation. Any a = codec.decode_value(message.identity_token.principal_name(), GSS_NT_ExportedNameHelper.type()); byte[] encodedName = GSS_NT_ExportedNameHelper.extract(a); // Decode the principal name. threadLocal.incomingPrincipalName = CSIv2Util.decodeGssExportedName(encodedName); if (threadLocal.incomingPrincipalName == null) { threadLocal.sasReply = createMsgCtxError(message.client_context_id, 2 /* major status: invalid mechanism */); throw IIOPLogger.ROOT_LOGGER.errorDecodingPrincipalName(); } } } threadLocal.sasReply = (threadLocal.contextId == 0) ? msgCtx0Accepted : createMsgCtxAccepted(threadLocal.contextId); threadLocal.sasReplyIsAccept = true; } } } catch (BAD_PARAM e) { // no service context with sasContextId: do nothing. } catch (FormatMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorDecodingContextData(this.name(), e); } catch (TypeMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorDecodingContextData(this.name(), e); } } @Override public void send_reply(ServerRequestInfo ri) { IIOPLogger.ROOT_LOGGER.tracef("send_reply: %s", ri.operation()); CurrentRequestInfo threadLocal = (CurrentRequestInfo) threadLocalData.get(); if (threadLocal.sasReply != null) { try { ServiceContext sc = new ServiceContext(sasContextId, codec.encode_value(threadLocal.sasReply)); ri.add_reply_service_context(sc, true); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } } @Override public void send_exception(ServerRequestInfo ri) { IIOPLogger.ROOT_LOGGER.tracef("send_exception: %s", ri.operation()); CurrentRequestInfo threadLocal = (CurrentRequestInfo) threadLocalData.get(); // The check below was added for interoperability with IONA's ASP 6.0, which throws an // ArrayIndexOutOfBoundsException when it receives an IIOP reply carrying both an application exception // and a SAS reply CompleteEstablishContext. The flag serves the purpose of refraining fromsending an SAS // accept (CompleteEstablishContext) reply together with an exception. // // The CSIv2 spec does not explicitly disallow an SAS accept in an IIOP exception reply. boolean interopIONA = Boolean.parseBoolean(CorbaORBService.getORBProperty(Constants.INTEROP_IONA)); if (threadLocal.sasReply != null && !interopIONA) { try { ServiceContext sc = new ServiceContext(sasContextId, codec.encode_value(threadLocal.sasReply)); ri.add_reply_service_context(sc, true); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } } @Override public void send_other(ServerRequestInfo ri) { // Do nothing. According to the SAS spec, LOCATION_FORWARD reply carries no SAS message. } }
17,752
38.276549
141
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIv2Policy.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.CORBA.Policy; import org.omg.IOP.Codec; import org.omg.IOP.TaggedComponent; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.service.CorbaORBService; /** * <p> * Implements a {@code org.omg.CORBA.Policy} that stores CSIv2 IOR security info. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class CSIv2Policy extends LocalObject implements Policy { // TODO: contact request@omg.org to get a policy type public static final int TYPE = 0x87654321; private TaggedComponent sslTaggedComponent; private TaggedComponent secTaggedComponent; /** * <p> * Creates an instance of {@code CSIv2Policy} with the specified tagged components. * </p> * * @param sslTaggedComponent a {@code TaggedComponent} that contains the encoded SSL info. * @param secTaggedComponent a {@code TaggedComponent} that contains the encoded CSIv2 security info. */ public CSIv2Policy(TaggedComponent sslTaggedComponent, TaggedComponent secTaggedComponent) { this.sslTaggedComponent = sslTaggedComponent; this.secTaggedComponent = secTaggedComponent; } /** * <p> * Creates an instance of {@code CSIv2Policy} with the specified metadata and codec. * </p> * * @param metadata an object containing all the CSIv2 security info. * @param codec the {@code Codec} used to encode the metadata when creating the tagged components. */ public CSIv2Policy(IORSecurityConfigMetaData metadata, Codec codec) { IIOPLogger.ROOT_LOGGER.debugf("IOR security config metadata: %s",metadata); // convert the ior metadata to a cached security tagged component. try { // get the singleton orb. ORB orb = ORB.init(); String sslPortString = CorbaORBService.getORBProperty(Constants.ORB_SSL_PORT); int sslPort = sslPortString == null ? 0 : Integer.parseInt(sslPortString); this.sslTaggedComponent = CSIv2Util.createSSLTaggedComponent(metadata, codec, sslPort, orb); this.secTaggedComponent = CSIv2Util.createSecurityTaggedComponent(metadata, codec, sslPort, orb); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } /** * <p> * Return a copy of the cached SSL {@code TaggedComponent}. * </p> * * @return a copy of the cached SSL {@code TaggedComponent}. */ public TaggedComponent getSSLTaggedComponent() { return CSIv2Util.createCopy(this.sslTaggedComponent); } /** * <p> * Return a copy of the cached CSI {@code TaggedComponent}. * </p> * * @return a copy of the cached CSI {@code TaggedComponent}. */ public TaggedComponent getSecurityTaggedComponent() { return CSIv2Util.createCopy(this.secTaggedComponent); } @Override public Policy copy() { return new CSIv2Policy(getSSLTaggedComponent(), getSecurityTaggedComponent()); } @Override public void destroy() { this.sslTaggedComponent = null; this.secTaggedComponent = null; } @Override public int policy_type() { return TYPE; } @Override public String toString() { return "CSIv2Policy[" + this.sslTaggedComponent + ", " + this.secTaggedComponent + "]"; } }
4,752
34.736842
109
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/SASCurrentImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.jboss.iiop.csiv2.SASCurrent; import org.omg.CORBA.LocalObject; import org.omg.CSI.IdentityToken; /** * <p> * This class implements {@code SASCurrent}. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class SASCurrentImpl extends LocalObject implements SASCurrent { private SASTargetInterceptor serverInterceptor; /** * <p> * Initialize the {@code SASCurrent} instance. * </p> * * @param serverInterceptor a reference to the {@code SASTargetInterceptor} that acts as a delegate for this * implementation. */ public void init(SASTargetInterceptor serverInterceptor) { this.serverInterceptor = serverInterceptor; } @Override public boolean context_received() { return this.serverInterceptor.sasContextReceived(); } @Override public boolean client_authentication_info_received() { return this.serverInterceptor.authenticationTokenReceived(); } @Override public byte[] get_incoming_username() { return this.serverInterceptor.getIncomingUsername(); } @Override public byte[] get_incoming_password() { return this.serverInterceptor.getIncomingPassword(); } @Override public byte[] get_incoming_target_name() { return this.serverInterceptor.getIncomingTargetName(); } @Override public IdentityToken get_incoming_identity() { return this.serverInterceptor.getIncomingIdentity(); } @Override public int get_incoming_identity_token_type() { return this.serverInterceptor.getIncomingIdentity().discriminator(); } @Override public byte[] get_incoming_principal_name() { return this.serverInterceptor.getIncomingPrincipalName(); } @Override public void reject_incoming_context() { this.serverInterceptor.rejectIncomingContext(); } }
3,083
30.793814
112
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIv2Util.java
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import java.nio.charset.StandardCharsets; import org.ietf.jgss.GSSException; import org.ietf.jgss.Oid; import org.jboss.metadata.ejb.jboss.IORASContextMetaData; import org.jboss.metadata.ejb.jboss.IORSASContextMetaData; import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData; import org.jboss.metadata.ejb.jboss.IORTransportConfigMetaData; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.ORB; import org.omg.CSI.ITTAnonymous; import org.omg.CSI.ITTDistinguishedName; import org.omg.CSI.ITTPrincipalName; import org.omg.CSI.ITTX509CertChain; import org.omg.CSIIOP.AS_ContextSec; import org.omg.CSIIOP.CompoundSecMech; import org.omg.CSIIOP.CompoundSecMechList; import org.omg.CSIIOP.CompoundSecMechListHelper; import org.omg.CSIIOP.Confidentiality; import org.omg.CSIIOP.DetectMisordering; import org.omg.CSIIOP.DetectReplay; import org.omg.CSIIOP.EstablishTrustInClient; import org.omg.CSIIOP.EstablishTrustInTarget; import org.omg.CSIIOP.IdentityAssertion; import org.omg.CSIIOP.Integrity; import org.omg.CSIIOP.SAS_ContextSec; import org.omg.CSIIOP.ServiceConfiguration; import org.omg.CSIIOP.TAG_TLS_SEC_TRANS; import org.omg.CSIIOP.TLS_SEC_TRANS; import org.omg.CSIIOP.TLS_SEC_TRANSHelper; import org.omg.CSIIOP.TransportAddress; import org.omg.GSSUP.GSSUPMechOID; import org.omg.GSSUP.InitialContextToken; import org.omg.GSSUP.InitialContextTokenHelper; import org.omg.IOP.Codec; import org.omg.IOP.TAG_CSI_SEC_MECH_LIST; import org.omg.IOP.TAG_NULL_TAG; import org.omg.IOP.TaggedComponent; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.PortableInterceptor.ClientRequestInfo; import org.omg.SSLIOP.SSL; import org.omg.SSLIOP.SSLHelper; import org.omg.SSLIOP.TAG_SSL_SEC_TRANS; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.service.CorbaORBService; /** * <p> * This class defines utility methods for creating, comparing, encoding and decoding CSIv2 components. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public final class CSIv2Util { /** * DER-encoded ASN.1 representation of the GSSUP mechanism OID. */ private static final byte[] gssUpMechOidArray = createGSSUPMechOID(); /** * <p> * Private constructor to implement the singleton pattern. * </p> */ private CSIv2Util() { } /** * <p> * Make a deep copy of an {@code IOP:TaggedComponent}. * </p> * * @param tc the {@code TaggedComponent} to be copied. * @return a reference to the created copy. */ public static TaggedComponent createCopy(TaggedComponent tc) { TaggedComponent copy = null; if (tc != null) { byte[] buf = new byte[tc.component_data.length]; System.arraycopy(tc.component_data, 0, buf, 0, tc.component_data.length); copy = new TaggedComponent(tc.tag, buf); } return copy; } /** * <p> * Return a top-level {@code IOP::TaggedComponent} to be stuffed into an IOR, containing a structure * {@code SSLIOP::SSL}, tagged as {@code TAG_SSL_SEC_TRANS}. * </p> * <p> * Should be called with non-null metadata, in which case we probably don't want to include security info in the IOR. * </p> * * @param metadata the metadata object that contains the SSL configuration info. * @param codec the {@code Codec} used to encode the SSL component. * @param sslPort an {@code int} representing the SSL port. * @param orb a reference to the running {@code ORB}. * @return a {@code TaggedComponent} representing the encoded SSL component. */ public static TaggedComponent createSSLTaggedComponent(IORSecurityConfigMetaData metadata, Codec codec, int sslPort, ORB orb) { if (metadata == null) { IIOPLogger.ROOT_LOGGER.debug("Method createSSLTaggedComponent() called with null metadata"); return null; } if (sslPort == 0) { // no support for transport security. return null; } TaggedComponent tc; try { int supports = createTargetSupports(metadata.getTransportConfig()); int requires = createTargetRequires(metadata.getTransportConfig()); SSL ssl = new SSL((short) supports, (short) requires, (short) sslPort); Any any = orb.create_any(); SSLHelper.insert(any, ssl); byte[] componentData = codec.encode_value(any); tc = new TaggedComponent(TAG_SSL_SEC_TRANS.value, componentData); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } return tc; } /** * <p> * Return a top-level {@code IOP:TaggedComponent} to be stuffed into an IOR, containing a {@code org.omg.CSIIOP}. * {@code CompoundSecMechList}, tagged as {@code TAG_CSI_SEC_MECH_LIST}. Only one such component can exist inside * an IOR. * </p> * <p> * Should be called with non-null metadata, in which case we probably don't want to include security info in the IOR. * </p> * * @param metadata the metadata object that contains the CSIv2 security configuration info. * @param codec the {@code Codec} used to encode the CSIv2 security component. * @param sslPort an {@code int} representing the SSL port. * @param orb a reference to the running {@code ORB}. * @return a {@code TaggedComponent} representing the encoded CSIv2 security component. */ public static TaggedComponent createSecurityTaggedComponent(IORSecurityConfigMetaData metadata, Codec codec, int sslPort, ORB orb) { if (metadata == null) { IIOPLogger.ROOT_LOGGER.debug("Method createSecurityTaggedComponent() called with null metadata"); return null; } TaggedComponent tc; // get the the supported security mechanisms. CompoundSecMech[] mechList = createCompoundSecMechanisms(metadata, codec, sslPort, orb); // the above is wrapped into a org.omg.CSIIOP.CompoundSecMechList structure, which is NOT a CompoundSecMech[]. // we don't support stateful/reusable security contexts (false). CompoundSecMechList csmList = new CompoundSecMechList(false, mechList); // finally, the CompoundSecMechList must be encoded as a TaggedComponent try { Any any = orb.create_any(); CompoundSecMechListHelper.insert(any, csmList); byte[] b = codec.encode_value(any); tc = new TaggedComponent(TAG_CSI_SEC_MECH_LIST.value, b); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } return tc; } /** * <p> * Create a {@code org.omg.CSIIOP.CompoundSecMechanisms} which is a sequence of {@code CompoundSecMech}. Here we only * support one security mechanism. * </p> * * @param metadata the metadata object that contains the CSIv2 security configuration info. * @param codec the {@code Codec} used to encode the CSIv2 security component. * @param sslPort an {@code int} representing the SSL port. * @param orb a reference to the running {@code ORB}. * @return the constructed {@code CompoundSecMech} array. */ public static CompoundSecMech[] createCompoundSecMechanisms(IORSecurityConfigMetaData metadata, Codec codec, int sslPort, ORB orb) { // support just 1 security mechanism for now (and ever). CompoundSecMech[] csmList = new CompoundSecMech[1]; // a CompoundSecMech contains: target_requires, transport_mech, as_context_mech, sas_context_mech. TaggedComponent transport_mech = createTransportMech(metadata.getTransportConfig(), codec, sslPort, orb); // create AS Context. AS_ContextSec asContext = createAuthenticationServiceContext(metadata); // create SAS Context. SAS_ContextSec sasContext = createSecureAttributeServiceContext(metadata); // create target_requires bit field (AssociationOption) can't read directly the transport_mech TaggedComponent. int target_requires = createTargetRequires(metadata.getTransportConfig()) | asContext.target_requires | sasContext.target_requires; CompoundSecMech csm = new CompoundSecMech((short) target_requires, transport_mech, asContext, sasContext); csmList[0] = csm; return csmList; } /** * <p> * Create the Secure Attribute Service (SAS) context included in a {@code CompoundSecMech} definition. * </p> * * @param metadata the metadata object that contains the CSIv2 security configuration info. * @return the constructed {@code SAS_ContextSec} instance. */ public static SAS_ContextSec createSecureAttributeServiceContext(IORSecurityConfigMetaData metadata) { SAS_ContextSec context; // context contains target_supports, target_requires, privilige_authorities, supported_naming_mechanisms, supported_identity_types. int support = 0; int require = 0; ServiceConfiguration[] privilAuth = new ServiceConfiguration[0]; byte[][] supNamMechs = {}; int supIdenTypes = 0; // 0 means ITTAbsent // the the SasContext metadata. IORSASContextMetaData sasMeta = metadata.getSasContext(); // if no SAS context metadata, or caller propagation is not supported, we return with a more or less empty sas context. if (sasMeta == null || sasMeta.getCallerPropagation().equals(IORSASContextMetaData.CALLER_PROPAGATION_NONE)) { context = new SAS_ContextSec((short) support, (short) require, privilAuth, supNamMechs, supIdenTypes); } else { support = IdentityAssertion.value; // supporting GSSUP (username/password) naming mechanism. byte[] upMech = createGSSUPMechOID(); supNamMechs = new byte[1][upMech.length]; System.arraycopy(upMech, 0, supNamMechs[0], 0, upMech.length); // since we support IdentityAssertion we need to specify supported identity types. CTS says we need them all supIdenTypes = ITTAnonymous.value | ITTPrincipalName.value | ITTX509CertChain.value | ITTDistinguishedName.value; context = new SAS_ContextSec((short) support, (short) require, privilAuth, supNamMechs, supIdenTypes); } return context; } /** * <p> * Create the client Authentication Service (AS) context included in a {@code CompoundSecMech} definition. * </p> * * @param metadata the metadata object that contains the CSIv2 security configuration info. * @return the constructed {@code AS_ContextSec} instance. */ public static AS_ContextSec createAuthenticationServiceContext(IORSecurityConfigMetaData metadata) { AS_ContextSec context; // the content of the context. int support = 0; int require = 0; byte[] clientAuthMech = {}; byte[] targetName = {}; IORASContextMetaData asMeta = metadata.getAsContext(); // if no AS context metatada exists, or authentication method "none" is specified, we can produce an empty AS context. if (asMeta == null || asMeta.getAuthMethod().equals(IORASContextMetaData.AUTH_METHOD_NONE)) { context = new AS_ContextSec((short) support, (short) require, clientAuthMech, targetName); } else { // we do support. support = EstablishTrustInClient.value; // required depends on the metadata. if (asMeta.isRequired()) { require = EstablishTrustInClient.value; } // we only support GSSUP authentication method. clientAuthMech = createGSSUPMechOID(); // finally, encode the "realm" name as a CSI.GSS_NT_ExportedName. // clientAuthMech should contain the DER encoded GSSUPMechOID at this point. String realm = asMeta.getRealm(); targetName = createGSSExportedName(clientAuthMech, realm.getBytes(StandardCharsets.UTF_8)); context = new AS_ContextSec((short) support, (short) require, clientAuthMech, targetName); } return context; } /** * <p> * Create a transport mechanism {@code TaggedComponent} to be stuffed into a {@code CompoundSecMech}. * </p> * <p> * If no {@code TransportConfig} metadata is specified, or ssl port is negative, or the specified metadata indicates * that transport config is not supported, then a {@code TAG_NULL_TAG} (empty) {@code TaggedComponent} will be returned. * </p> * <p> * Otherwise a {@code org.omg.CSIIOP.TLS_SEC_TRANS}, tagged as {@code TAG_TLS_SEC_TRANS} will be returned, indicating support * for TLS/SSL as a CSIv2 transport mechanism. * </p> * <p> * Multiple {@code TransportAddress} may be included in the SSL info (host/port pairs), but we only include one. * </p> * * @param tconfig the transport configuration metadata. * @param codec the {@code Codec} used to encode the transport configuration. * @param sslPort an {@code int} representing the SSL port. * @param orb a reference to the running {@code ORB}. * @return the constructed {@code TaggedComponent}. */ public static TaggedComponent createTransportMech(IORTransportConfigMetaData tconfig, Codec codec, int sslPort, ORB orb) { TaggedComponent tc; // what we support and require as a target. int support = 0; int require = 0; if (tconfig != null) { require = createTargetRequires(tconfig); support = createTargetSupports(tconfig); } if (tconfig == null || support == 0 || sslPort == 0) { // no support for transport security. tc = new TaggedComponent(TAG_NULL_TAG.value, new byte[0]); } else { // my ip address. String host = CorbaORBService.getORBProperty(Constants.ORB_ADDRESS); // this will create only one transport address. TransportAddress[] taList = createTransportAddress(host, sslPort); TLS_SEC_TRANS tst = new TLS_SEC_TRANS((short) support, (short) require, taList); // The tricky part, we must encode TLS_SEC_TRANS into an octet sequence. try { Any any = orb.create_any(); TLS_SEC_TRANSHelper.insert(any, tst); byte[] b = codec.encode_value(any); tc = new TaggedComponent(TAG_TLS_SEC_TRANS.value, b); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } return tc; } /** * <p> * Create a {@code TransportAddress[]} with a single {@code TransportAddress}. * </p> * * @param host a {@code String} representing the address host. * @param port an {@code int} representing the address port. * @return the constructed {@code TransportAddress} array. */ public static TransportAddress[] createTransportAddress(String host, int port) { // idl type is unsigned sort, so we need this trick short short_port = (port > 32767) ? (short) (port - 65536) : (short) port; TransportAddress ta = new TransportAddress(host, short_port); TransportAddress[] taList = new TransportAddress[1]; taList[0] = ta; return taList; } /** * <p> * Create the bitmask of what the target requires. * </p> * * @param tc the transport configuration metadata. * @return an {@code int} representing the transport mechanism required by the target. */ public static int createTargetRequires(IORTransportConfigMetaData tc) { int requires = 0; if (tc != null) { if (tc.getIntegrity().equals(IORTransportConfigMetaData.INTEGRITY_REQUIRED)) { requires = requires | Integrity.value; } if (tc.getConfidentiality().equals(IORTransportConfigMetaData.CONFIDENTIALITY_REQUIRED)) { requires = requires | Confidentiality.value; } if (tc.getDetectMisordering().equalsIgnoreCase(IORTransportConfigMetaData.DETECT_MISORDERING_REQUIRED)) { requires = requires | DetectMisordering.value; } if (tc.getDetectReplay().equalsIgnoreCase(IORTransportConfigMetaData.DETECT_REPLAY_REQUIRED)) { requires = requires | DetectReplay.value; } // no EstablishTrustInTarget required - client decides if (tc.getEstablishTrustInClient().equals(IORTransportConfigMetaData.ESTABLISH_TRUST_IN_CLIENT_REQUIRED)) { requires = requires | EstablishTrustInClient.value; } } return requires; } /** * <p> * Create the bitmask of what the target supports. * </p> * * @param tc the transport configuration metadata. * @return an {@code int} representing the transport mechanisms supported by the target. */ public static int createTargetSupports(IORTransportConfigMetaData tc) { int supports = 0; if (tc != null) { if (!tc.getIntegrity().equals(IORTransportConfigMetaData.INTEGRITY_NONE)) { supports = supports | Integrity.value; } if (!tc.getConfidentiality().equals(IORTransportConfigMetaData.CONFIDENTIALITY_NONE)) { supports = supports | Confidentiality.value; } if (!tc.getDetectMisordering().equalsIgnoreCase(IORTransportConfigMetaData.DETECT_MISORDERING_NONE)) { supports = supports | DetectMisordering.value; } if (!tc.getDetectReplay().equalsIgnoreCase(IORTransportConfigMetaData.DETECT_REPLAY_NONE)) { supports = supports | DetectReplay.value; } if (!tc.getEstablishTrustInTarget().equals(IORTransportConfigMetaData.ESTABLISH_TRUST_IN_TARGET_NONE)) { supports = supports | EstablishTrustInTarget.value; } if (!tc.getEstablishTrustInClient().equals(IORTransportConfigMetaData.ESTABLISH_TRUST_IN_CLIENT_NONE)) { supports = supports | EstablishTrustInClient.value; } } return supports; } /** * <p> * Create an ASN.1, DER encoded representation for the GSSUP OID mechanism. * </p> * * @return the DER encoded representation of the GSSUP OID. */ public static byte[] createGSSUPMechOID() { // kudos to org.ietf.jgss.Oid for the Oid utility need to strip the "oid:" part of the GSSUPMechOID first. byte[] retval = {}; try { Oid oid = new Oid(GSSUPMechOID.value.substring(4)); retval = oid.getDER(); } catch (GSSException e) { IIOPLogger.ROOT_LOGGER.caughtExceptionEncodingGSSUPMechOID(e); } return retval; } /** * <p/> * Generate an exported name as specified in [RFC 2743], section 3.2 copied below: * <p/> * 3.2: Mechanism-Independent Exported Name Object Format * <p/> * This section specifies a mechanism-independent level of encapsulating representation for names exported via the * GSS_Export_name() call, including an object identifier representing the exporting mechanism. The format of names * encapsulated via this representation shall be defined within individual mechanism drafts. The Object Identifier * value to indicate names of this type is defined in Section 4.7 of this document. * <p/> * No name type OID is included in this mechanism-independent level of format definition, since (depending on * individual mechanism specifications) the enclosed name may be implicitly typed or may be explicitly typed using * a means other than OID encoding. * <p/> * The bytes within MECH_OID_LEN and NAME_LEN elements are represented most significant byte first (equivalently, * in IP network byte order). * <p/> * Length Name Description * <p/> * 2 TOK_ID Token Identifier * For exported name objects, this must be hex 04 01. * 2 MECH_OID_LEN Length of the Mechanism OID * MECH_OID_LEN MECH_OID Mechanism OID, in DER * 4 NAME_LEN Length of name * NAME_LEN NAME Exported name; format defined in applicable mechanism draft. * <p/> * A concrete example of the contents of an exported name object, derived from the Kerberos Version 5 mechanism, is * as follows: * <p/> * 04 01 00 0B 06 09 2A 86 48 86 F7 12 01 02 02 hx xx xx xl pp qq ... zz * <p/> * ... * * @param oid the DER encoded OID. * @param name the name to be converted to {@code GSSExportedName}. * @return a {@code byte[]} representing the exported name. */ public static byte[] createGSSExportedName(byte[] oid, byte[] name) { int olen = oid.length; int nlen = name.length; // size according to spec. int size = 2 + 2 + olen + 4 + nlen; // allocate space for the exported name. byte[] buf = new byte[size]; // index. int i = 0; // standard header. buf[i++] = 0x04; buf[i++] = 0x01; // encode oid length. buf[i++] = (byte) (olen & 0xFF00); buf[i++] = (byte) (olen & 0x00FF); // copy the oid in the exported name buffer. System.arraycopy(oid, 0, buf, i, olen); i += olen; // encode the name length in the exported buffer. buf[i++] = (byte) (nlen & 0xFF000000); buf[i++] = (byte) (nlen & 0x00FF0000); buf[i++] = (byte) (nlen & 0x0000FF00); buf[i++] = (byte) (nlen & 0x000000FF); // finally, copy the name bytes. System.arraycopy(name, 0, buf, i, nlen); return buf; } /** * <p> * ASN.1-encode an {@code InitialContextToken} as defined in RFC 2743, Section 3.1, "Mechanism-Independent Token * Format", pp. 81-82. The encoded token contains the ASN.1 tag 0x60, followed by a token length (which is itself * stored in a variable-length format and takes 1 to 5 bytes), the GSSUP mechanism identifier, and a mechanism-specific * token, which in this case is a CDR encapsulation of the GSSUP {@code InitialContextToken} in the {@code authToken} * parameter. * </p> * * @param authToken the {@code InitialContextToken} to be encoded. * @param codec the {@code Codec} used to encode the token. * @return a {@code byte[]} representing the encoded token. */ public static byte[] encodeInitialContextToken(InitialContextToken authToken, Codec codec) { byte[] out; Any any = ORB.init().create_any(); InitialContextTokenHelper.insert(any, authToken); try { out = codec.encode_value(any); } catch (Exception e) { return new byte[0]; } int length = out.length + gssUpMechOidArray.length; int n; if (length < (1 << 7)) { n = 0; } else if (length < (1 << 8)) { n = 1; } else if (length < (1 << 16)) { n = 2; } else if (length < (1 << 24)) { n = 3; } else {// if (length < (1 << 32)) n = 4; } byte[] encodedToken = new byte[2 + n + length]; encodedToken[0] = 0x60; if (n == 0) { encodedToken[1] = (byte) length; } else { encodedToken[1] = (byte) (n | 0x80); switch (n) { case 1: encodedToken[2] = (byte) length; break; case 2: encodedToken[2] = (byte) (length >> 8); encodedToken[3] = (byte) length; break; case 3: encodedToken[2] = (byte) (length >> 16); encodedToken[3] = (byte) (length >> 8); encodedToken[4] = (byte) length; break; default: // case 4: encodedToken[2] = (byte) (length >> 24); encodedToken[3] = (byte) (length >> 16); encodedToken[4] = (byte) (length >> 8); encodedToken[5] = (byte) length; } } System.arraycopy(gssUpMechOidArray, 0, encodedToken, 2 + n, gssUpMechOidArray.length); System.arraycopy(out, 0, encodedToken, 2 + n + gssUpMechOidArray.length, out.length); return encodedToken; } /** * <p> * Decodes an ASN.1-encoded {@code InitialContextToken}. See {@code encodeInitialContextToken} for a description of * the encoded token format. * </p> * * @param encodedToken the encoded token. * @param codec the {@code Codec} used to decode the token. * @return the decoded {@code InitialContextToken} instance. * @see #encodeInitialContextToken(InitialContextToken, Codec) */ public static InitialContextToken decodeInitialContextToken(byte[] encodedToken, Codec codec) { if (encodedToken[0] != 0x60) return null; int encodedLength = 0; int n = 0; if (encodedToken[1] >= 0) encodedLength = encodedToken[1]; else { n = encodedToken[1] & 0x7F; for (int i = 1; i <= n; i++) { encodedLength += (encodedToken[1 + i] & 0xFF) << (n - i) * 8; } } int length = encodedLength - gssUpMechOidArray.length; byte[] encodedInitialContextToken = new byte[length]; System.arraycopy(encodedToken, 2 + n + gssUpMechOidArray.length, encodedInitialContextToken, 0, length); Any any; try { any = codec.decode_value(encodedInitialContextToken, InitialContextTokenHelper.type()); } catch (Exception e) { return null; } return InitialContextTokenHelper.extract(any); } /** * <p> * ASN.1-encodes a GSS exported name with the GSSUP mechanism OID. See {@code createGSSExportedName} for a * description of the encoding format. * </p> * * @param name the exported name to be encoded. * @return a {@code byte[]} representing the encoded exported name. * @see #createGSSExportedName(byte[], byte[]) */ public static byte[] encodeGssExportedName(byte[] name) { return createGSSExportedName(gssUpMechOidArray, name); } /** * <p> * Decodes a GSS exported name that has been encoded with the GSSUP mechanism OID. See {@code createGSSExportedName} * for a description of the encoding format. * </p> * * @param encodedName the encoded exported name. * @return a {@code byte[]} representing the decoded exported name. * @see #createGSSExportedName(byte[], byte[]) */ public static byte[] decodeGssExportedName(byte[] encodedName) { if (encodedName[0] != 0x04 || encodedName[1] != 0x01) return null; int mechOidLength = (encodedName[2] & 0xFF) << 8; //MECH_OID_LEN mechOidLength += (encodedName[3] & 0xFF); // MECH_OID_LEN byte[] oidArray = new byte[mechOidLength]; System.arraycopy(encodedName, 4, oidArray, 0, mechOidLength); for (int i = 0; i < mechOidLength; i++) { if (gssUpMechOidArray[i] != oidArray[i]) { return null; } } int offset = 4 + mechOidLength; int nameLength = (encodedName[offset] & 0xFF) << 24; nameLength += (encodedName[++offset] & 0xFF) << 16; nameLength += (encodedName[++offset] & 0xFF) << 8; nameLength += (encodedName[++offset] & 0xFF); byte[] name = new byte[nameLength]; System.arraycopy(encodedName, ++offset, name, 0, nameLength); return name; } /** * <p> * Helper method to be called from a client request interceptor. The {@code ri} parameter refers to the current * request. This method returns the first {@code CompoundSecMech} found in the target IOR such that * <ul> * <li>all {@code CompoundSecMech} requirements are satisfied by the options in the {@code clientSupports} * parameter, and</li> * <li>every requirement in the {@code clientRequires} parameter is satisfied by the {@code CompoundSecMech}. * </li> * </ul> * The method returns null if the target IOR contains no {@code CompoundSecMech}s or if no matching * {@code CompoundSecMech} is found. * </p> * <p> * Since this method is intended to be called from a client request interceptor, it converts unexpected exceptions * into {@code MARSHAL} exceptions. * </p> * * @param ri a reference to the current {@code ClientRequestInfo}. * @param codec the {@code Codec} used to decode the CSIv2 components. * @param clientSupports the client supported transport options that must be satisfied by the {@code CompoundSecMech}. * @param clientRequires the client required transport options that must be satisfied by the {@code CompoundSecMech}. * @return the {@code CompoundSecMech} instance that satisfies all client options, or {@code null} if no such object * can be found. */ public static CompoundSecMech getMatchingSecurityMech(ClientRequestInfo ri, Codec codec, short clientSupports, short clientRequires) { CompoundSecMechList csmList; try { TaggedComponent tc = ri.get_effective_component(TAG_CSI_SEC_MECH_LIST.value); Any any = codec.decode_value(tc.component_data, CompoundSecMechListHelper.type()); csmList = CompoundSecMechListHelper.extract(any); // look for the first matching security mech. for (int i = 0; i < csmList.mechanism_list.length; i++) { CompoundSecMech securityMech = csmList.mechanism_list[i]; AS_ContextSec authConfig = securityMech.as_context_mech; if ((EstablishTrustInTarget.value & (clientRequires ^ authConfig.target_supports) & ~authConfig.target_supports) != 0) { // client requires EstablishTrustInTarget, but target does not support it: skip this securityMech. continue; } if ((EstablishTrustInClient.value & (authConfig.target_requires ^ clientSupports) & ~clientSupports) != 0) { // target requires EstablishTrustInClient, but client does not support it: skip this securityMech. continue; } SAS_ContextSec identityConfig = securityMech.sas_context_mech; if ((IdentityAssertion.value & (identityConfig.target_requires ^ clientSupports) & ~clientSupports) != 0) { // target requires IdentityAssertion, but client does not support it: skip this securityMech continue; } // found matching securityMech. return securityMech; } // no matching securityMech was found. return null; } catch (BAD_PARAM e) { // no component with TAG_CSI_SEC_MECH_LIST was found. return null; } catch (org.omg.IOP.CodecPackage.TypeMismatch e) { // unexpected exception in codec throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } catch (org.omg.IOP.CodecPackage.FormatMismatch e) { // unexpected exception in codec throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } /** * <p> * Generate a string representation of the {@code CompoundSecMech}. * </p> * * @param securityMech the {@code CompoundSecMech} to create the string for. * @param builder the buffer to write to. */ public static void toString(CompoundSecMech securityMech, StringBuilder builder) { AS_ContextSec asMech = securityMech != null ? securityMech.as_context_mech : null; SAS_ContextSec sasMech = securityMech != null ? securityMech.sas_context_mech : null; if (securityMech != null) { builder.append("CompoundSecMech["); builder.append("target_requires: "); builder.append(securityMech.target_requires); if (asMech != null) { builder.append("AS_ContextSec["); builder.append("client_authentication_mech: "); builder.append(new String(asMech.client_authentication_mech, StandardCharsets.UTF_8)); builder.append(", target_name: "); builder.append(new String(asMech.target_name, StandardCharsets.UTF_8)); builder.append(", target_requires: "); builder.append(asMech.target_requires); builder.append(", target_supports: "); builder.append(asMech.target_supports); builder.append("]"); } if (sasMech != null) { builder.append("SAS_ContextSec["); builder.append("supported_identity_types: "); builder.append(sasMech.supported_identity_types); builder.append(", target_requires: "); builder.append(sasMech.target_requires); builder.append(", target_supports: "); builder.append(sasMech.target_supports); builder.append("]"); } builder.append("]"); } } }
35,601
40.835488
139
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/ElytronSASClientInterceptor.java
/* * Copyright 2017 Red Hat, Inc. * * 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.wildfly.iiop.openjdk.csiv2; import static java.security.AccessController.doPrivileged; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.AccessController; import java.security.Principal; import java.security.PrivilegedAction; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.CompletionStatus; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.CSI.AuthorizationElement; import org.omg.CSI.EstablishContext; import org.omg.CSI.GSS_NT_ExportedNameHelper; import org.omg.CSI.ITTAnonymous; import org.omg.CSI.IdentityToken; import org.omg.CSI.MTContextError; import org.omg.CSI.SASContextBody; import org.omg.CSI.SASContextBodyHelper; import org.omg.CSIIOP.CompoundSecMech; import org.omg.CSIIOP.EstablishTrustInClient; import org.omg.CSIIOP.IdentityAssertion; import org.omg.GSSUP.InitialContextToken; import org.omg.IOP.Codec; import org.omg.IOP.ServiceContext; import org.omg.IOP.CodecPackage.FormatMismatch; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.IOP.CodecPackage.TypeMismatch; import org.omg.PortableInterceptor.ClientRequestInfo; import org.omg.PortableInterceptor.ClientRequestInterceptor; import org.omg.PortableInterceptor.ForwardRequest; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.AuthenticationContextConfigurationClient; import org.wildfly.security.auth.client.MatchRule; import org.wildfly.security.auth.principal.AnonymousPrincipal; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.manager.WildFlySecurityManager; import com.sun.corba.se.impl.interceptors.ClientRequestInfoImpl; import com.sun.corba.se.impl.transport.SocketOrChannelContactInfoImpl; import com.sun.corba.se.pept.transport.ContactInfo; import com.sun.corba.se.spi.transport.CorbaConnection; /** * This implementation of {@code org.omg.PortableInterceptor.ClientRequestInterceptor} inserts the security attribute * service (SAS) context into outgoing IIOP requests and handles the SAS messages received from the target security * service in the SAS context of incoming IIOP replies. * <p/> * When creating the SAS context, this implementation looks for an Elytron {@link AuthenticationConfiguration} that matches * the target URI (in the form iiop://hostname:port) and then uses the configuration to obtain the security info (like * username and password) that is inserted into the security tokens that are set in the SAS context. * <p/> * The type of security tokens that are constructed depends on the target security requirements: * <ul> * <li> * If the target supports identity propagation, the identity obtained from the Elytron configuration that matches * the target URI to build the {@link IdentityToken} that is inserted into the SAS context. This usually means using * a configuration backed by a security domain so that the current authenticated identity in that domain is used * to build the identity token. * </li> * <li> * If in addition to the identity token the target requires username/password authentication, it means the target * expects this runtime (server) to identify itself using its own username and credentials. Once this runtime * has been authenticated, the identity contained in the identity token is used as a run-as identity. * <p/> * In terms of configuration, it must match the target URI and it is usually a config that defines this * server's auth-name and associated credential via credential-reference. * </li> * <li> * If the target doesn't support identity propagation but supports username/password authentication, the identity * and credentials obtained from the Elytron configuration that matches the target URI to build * the {@link InitialContextToken}. Again, this usually means using a configuration backed by a security domain so * that the current authenticated identity in that domain and its associated credentials are used to build the * initial context token. * </li> * </ul> */ public class ElytronSASClientInterceptor extends LocalObject implements ClientRequestInterceptor { private static final int SAS_CONTEXT_ID = org.omg.IOP.SecurityAttributeService.value; private static final String AUTHENTICATION_CONTEXT_CAPABILITY = "org.wildfly.security.authentication-context"; private static final RuntimeCapability<Void> AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY = RuntimeCapability .Builder.of(AUTHENTICATION_CONTEXT_CAPABILITY, true, AuthenticationContext.class) .build(); private static final AuthenticationContextConfigurationClient AUTH_CONFIG_CLIENT = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION); private static final IdentityToken ABSENT_IDENTITY_TOKEN; static { ABSENT_IDENTITY_TOKEN = new IdentityToken(); ABSENT_IDENTITY_TOKEN.absent(true); } private static final byte[] NO_AUTHENTICATION_TOKEN = {}; private static final AuthorizationElement[] NO_AUTHORIZATION_TOKEN = {}; private static String authenticationContextName; public static void setAuthenticationContextName(final String authenticationContextName) { ElytronSASClientInterceptor.authenticationContextName = authenticationContextName; } private Codec codec; private AuthenticationContext authContext; public ElytronSASClientInterceptor(final Codec codec) { this.codec = codec; // initialize the authentication context. final ServiceContainer container = this.currentServiceContainer(); if(authenticationContextName != null) { final ServiceName authContextServiceName = AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY.getCapabilityServiceName(authenticationContextName); this.authContext = (AuthenticationContext) container.getRequiredService(authContextServiceName).getValue(); } else { this.authContext = null; } } @Override public void send_request(ClientRequestInfo ri) throws ForwardRequest { try { CompoundSecMech secMech = CSIv2Util.getMatchingSecurityMech(ri, codec, EstablishTrustInClient.value, /* client supports */ (short) 0 /* client requires */); if (secMech == null) { return; } // these "null tokens" will be changed if needed. IdentityToken identityToken = ABSENT_IDENTITY_TOKEN; byte[] encodedAuthenticationToken = NO_AUTHENTICATION_TOKEN; final URI uri = this.getURI(ri); if(uri == null) { return; } SecurityDomain domain = getCurrentSecurityDomain(); SecurityIdentity currentIdentity = null; if(domain != null) { currentIdentity = domain.getCurrentSecurityIdentity(); } final AuthenticationContext authContext; if(this.authContext != null) { authContext = this.authContext; } else if(currentIdentity == null || currentIdentity.isAnonymous()) { authContext = AuthenticationContext.captureCurrent(); } else { authContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.empty().useForwardedIdentity(domain)); } if ((secMech.sas_context_mech.target_supports & IdentityAssertion.value) != 0) { final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null); final Principal principal = AUTH_CONFIG_CLIENT.getPrincipal(configuration); if (principal != null && principal != AnonymousPrincipal.getInstance()) { // The name scope needs to be externalized. String name = principal.getName(); if (name.indexOf('@') < 0) { name += "@default"; // hardcoded (REVISIT!) } byte[] principalName = name.getBytes(StandardCharsets.UTF_8); // encode the principal name as mandated by RFC2743. byte[] encodedName = CSIv2Util.encodeGssExportedName(principalName); // encapsulate the encoded name. Any any = ORB.init().create_any(); byte[] encapsulatedEncodedName; GSS_NT_ExportedNameHelper.insert(any, encodedName); try { encapsulatedEncodedName = codec.encode_value(any); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } // create identity token. identityToken = new IdentityToken(); identityToken.principal_name(encapsulatedEncodedName); } else if ((secMech.sas_context_mech.supported_identity_types & ITTAnonymous.value) != 0) { // no run-as or caller identity and the target supports ITTAnonymous: use the anonymous identity. identityToken = new IdentityToken(); identityToken.anonymous(true); } // target might require an additional initial context token with a username/password pair for authentication. if ((secMech.as_context_mech.target_requires & EstablishTrustInClient.value) != 0) { encodedAuthenticationToken = this.createInitialContextToken(uri, secMech); } } else if ((secMech.as_context_mech.target_supports & EstablishTrustInClient.value) != 0) { // target doesn't require an identity token but supports username/password authentication - try to build // an initial context token using the configuration. encodedAuthenticationToken = this.createInitialContextToken(uri, secMech); } if (identityToken != ABSENT_IDENTITY_TOKEN || encodedAuthenticationToken != NO_AUTHENTICATION_TOKEN) { // at least one non-null token was created, create EstablishContext message with it. EstablishContext message = new EstablishContext(0, // stateless ctx id NO_AUTHORIZATION_TOKEN, identityToken, encodedAuthenticationToken); // create SAS context with the EstablishContext message. SASContextBody contextBody = new SASContextBody(); contextBody.establish_msg(message); // stuff the SAS context into the outgoing request. final Any any = ORB.init().create_any(); SASContextBodyHelper.insert(any, contextBody); ServiceContext sc = new ServiceContext(SAS_CONTEXT_ID, codec.encode_value(any)); ri.add_request_service_context(sc, true /*replace existing context*/); } } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } @Override public void send_poll(ClientRequestInfo ri) { } @Override public void receive_reply(ClientRequestInfo ri) { try { ServiceContext sc = ri.get_reply_service_context(SAS_CONTEXT_ID); Any msg = codec.decode_value(sc.context_data, SASContextBodyHelper.type()); SASContextBody contextBody = SASContextBodyHelper.extract(msg); // At this point contextBody should contain a CompleteEstablishContext message, which does not require any // treatment. ContextError messages should arrive via receive_exception(). IIOPLogger.ROOT_LOGGER.tracef("receive_reply: got SAS reply, type %d", contextBody.discriminator()); if (contextBody.discriminator() == MTContextError.value) { // should not happen. throw IIOPLogger.ROOT_LOGGER.unexpectedContextErrorInSASReply(0, CompletionStatus.COMPLETED_YES); } } catch (BAD_PARAM e) { // no service context with sasContextId: do nothing } catch (FormatMismatch | TypeMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorParsingSASReply(e, 0, CompletionStatus.COMPLETED_YES); } } @Override public void receive_exception(ClientRequestInfo ri) throws ForwardRequest { try { ServiceContext sc = ri.get_reply_service_context(SAS_CONTEXT_ID); Any msg = codec.decode_value(sc.context_data, SASContextBodyHelper.type()); SASContextBody contextBody = SASContextBodyHelper.extract(msg); // At this point contextBody may contain either a CompleteEstablishContext message or a ContextError message. // Neither message requires any treatment. We decoded the context body just to check that it contains // a well-formed message. IIOPLogger.ROOT_LOGGER.tracef("receive_exception: got SAS reply, type %d", contextBody.discriminator()); } catch (BAD_PARAM e) { // no service context with sasContextId: do nothing. } catch (FormatMismatch | TypeMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorParsingSASReply(e, 0, CompletionStatus.COMPLETED_MAYBE); } } @Override public void receive_other(ClientRequestInfo ri) throws ForwardRequest { } @Override public String name() { return "ElytronSASClientInterceptor"; } @Override public void destroy() { } /** * Get a reference to the current {@link ServiceContainer}. * * @return a reference to the current {@link ServiceContainer}. */ private ServiceContainer currentServiceContainer() { if(WildFlySecurityManager.isChecking()) { return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION); } return CurrentServiceContainer.getServiceContainer(); } /** * Build an {@link URI} using the information extracted from the specified {@link ClientRequestInfo}. The format of * the URI built by this method is "iiop://hostname:port". * * @param clientRequestInfo the {@link ClientRequestInfo} used to obtain the target information necessary to build * the {@link URI}. * @return the constructed {@link URI} instance. * @throws URISyntaxException if a syntax error is found when building the {@link URI}. */ private URI getURI(final ClientRequestInfo clientRequestInfo) throws URISyntaxException { final StringBuilder builder = new StringBuilder("iiop:"); if (clientRequestInfo instanceof ClientRequestInfoImpl) { ClientRequestInfoImpl infoImpl = (ClientRequestInfoImpl) clientRequestInfo; CorbaConnection connection = (CorbaConnection) infoImpl.connection(); if(connection == null) { return null; } ContactInfo info = connection.getContactInfo(); if (info instanceof SocketOrChannelContactInfoImpl) { String hostname = ((SocketOrChannelContactInfoImpl) info).getHost(); if (hostname != null) builder.append("//").append(hostname); int port = ((SocketOrChannelContactInfoImpl) info).getPort(); if (port > 0) builder.append(":").append(port); } } else { return null; } return new URI(builder.toString()); } /** * Create an encoded {@link InitialContextToken} with an username/password pair obtained from an Elytron client configuration * matched by the specified {@link URI}. * * @param uri the target {@link URI}. * @param secMech a reference to the {@link CompoundSecMech} that was found in the {@link ClientRequestInfo}. * @return the encoded {@link InitialContextToken}, if a valid username is obtained from the matched configuration; * an empty {@code byte[]} otherwise; * @throws Exception if an error occurs while building the encoded {@link InitialContextToken}. */ private byte[] createInitialContextToken(final URI uri, final CompoundSecMech secMech) throws Exception { AuthenticationContext authContext = this.authContext == null ? AuthenticationContext.captureCurrent() : this.authContext; // obtain the configuration that matches the URI. final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null); // get the callback handler from the configuration and use it to obtain a username/password pair. final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration); final NameCallback nameCallback = new NameCallback("Username: "); final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false); try { handler.handle(new Callback[]{nameCallback, passwordCallback}); } catch (UnsupportedCallbackException e) { return NO_AUTHENTICATION_TOKEN; } // if the name callback contains a valid username we create the initial context token. if (nameCallback.getName() != null && !nameCallback.getName().equals(AnonymousPrincipal.getInstance().getName())) { byte[] encodedTargetName = secMech.as_context_mech.target_name; String name = nameCallback.getName(); if (name.indexOf('@') < 0) { byte[] decodedTargetName = CSIv2Util.decodeGssExportedName(encodedTargetName); String targetName = new String(decodedTargetName, StandardCharsets.UTF_8); name += "@" + targetName; // "@default" } byte[] username = name.getBytes(StandardCharsets.UTF_8); byte[] password = {}; if (passwordCallback.getPassword() != null) password = new String(passwordCallback.getPassword()).getBytes(StandardCharsets.UTF_8); // create the initial context token and ASN.1-encode it, as defined in RFC 2743. InitialContextToken authenticationToken = new InitialContextToken(username, password, encodedTargetName); return CSIv2Util.encodeInitialContextToken(authenticationToken, codec); } return NO_AUTHENTICATION_TOKEN; } private static SecurityDomain getCurrentSecurityDomain() { if (WildFlySecurityManager.isChecking()) { return doPrivileged((PrivilegedAction<SecurityDomain>) SecurityDomain::getCurrent); } return SecurityDomain.getCurrent(); } }
20,329
48.34466
150
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIv2IORInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.CSIIOP.DetectMisordering; import org.omg.CSIIOP.DetectReplay; import org.omg.CSIIOP.Integrity; import org.omg.IOP.Codec; import org.omg.IOP.TAG_INTERNET_IOP; import org.omg.IOP.TaggedComponent; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.PortableInterceptor.IORInfo; import org.omg.PortableInterceptor.IORInterceptor; import org.omg.SSLIOP.SSL; import org.omg.SSLIOP.SSLHelper; import org.omg.SSLIOP.TAG_SSL_SEC_TRANS; import org.wildfly.iiop.openjdk.Constants; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import org.wildfly.iiop.openjdk.service.CorbaORBService; import org.wildfly.iiop.openjdk.service.IORSecConfigMetaDataService; /** * <p> * Implements an {@code org.omg.PortableInterceptor.IORInterceptor} that inserts CSIv2 info into an IOR. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class CSIv2IORInterceptor extends LocalObject implements IORInterceptor { // The minimum set of security options supported by the SSL mechanism (These options cannot be turned off, so they are always supported). private static final int MIN_SSL_OPTIONS = Integrity.value | DetectReplay.value | DetectMisordering.value; private TaggedComponent defaultSSLComponent; private TaggedComponent defaultCSIComponent; /** * <p> * Creates an instance of {@code CSIv2IORInterceptor} with the specified codec. * </p> * * @param codec the {@code Codec} used to encode the IOR security components. */ public CSIv2IORInterceptor(Codec codec) { String sslPortString = CorbaORBService.getORBProperty(Constants.ORB_SSL_PORT); int sslPort = sslPortString == null ? 0 : Integer.parseInt(sslPortString); try { SSL ssl = new SSL((short) MIN_SSL_OPTIONS, (short) 0, /* required options */ (short) sslPort); ORB orb = ORB.init(); Any any = orb.create_any(); SSLHelper.insert(any, ssl); byte[] componentData = codec.encode_value(any); defaultSSLComponent = new TaggedComponent(TAG_SSL_SEC_TRANS.value, componentData); IORSecurityConfigMetaData iorSecurityConfigMetaData = IORSecConfigMetaDataService.getCurrent(); if (iorSecurityConfigMetaData == null) iorSecurityConfigMetaData = new IORSecurityConfigMetaData(); defaultCSIComponent = CSIv2Util.createSecurityTaggedComponent(iorSecurityConfigMetaData, codec, sslPort, orb); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } @Override public void destroy() { } @Override public void establish_components(IORInfo info) { // check if CSIv2 policy is in effect for this IOR. CSIv2Policy csiv2Policy = null; try { csiv2Policy = (CSIv2Policy) info.get_effective_policy(CSIv2Policy.TYPE); } catch (BAD_PARAM e) { IIOPLogger.ROOT_LOGGER.debug("CSIv2Policy not found in IORInfo"); } catch (Exception e) { IIOPLogger.ROOT_LOGGER.failedToFetchCSIv2Policy(e); } boolean interopIONA = Boolean.parseBoolean(CorbaORBService.getORBProperty(Constants.INTEROP_IONA)); if (csiv2Policy != null) { // if csiv2Policy effective, stuff a copy of the TaggedComponents already created by the CSIv2Policy into the IOR's IIOP profile. TaggedComponent sslComponent = csiv2Policy.getSSLTaggedComponent(); // if interop with IONA ASP is on, don't add the SSL component to the IOR. if (sslComponent != null && !interopIONA) { info.add_ior_component_to_profile(sslComponent, TAG_INTERNET_IOP.value); } TaggedComponent csiv2Component = csiv2Policy.getSecurityTaggedComponent(); if (csiv2Component != null) { info.add_ior_component_to_profile(csiv2Component, TAG_INTERNET_IOP.value); } } else { if (defaultSSLComponent != null && !interopIONA) { // otherwise stuff the default SSL component (with the minimum set of SSL options) into the IOR's IIOP profile. info.add_ior_component_to_profile(defaultSSLComponent, TAG_INTERNET_IOP.value); } if (defaultCSIComponent != null) { // and stuff the default CSI component (with the minimum set of CSI options) into the IOR's IIOP profile. info.add_ior_component_to_profile(defaultCSIComponent, TAG_INTERNET_IOP.value); } } } @Override public String name() { return CSIv2IORInterceptor.class.getName(); } }
6,073
42.697842
141
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/ElytronSASInitializer.java
/* * Copyright 2017 Red Hat, Inc. * * 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.wildfly.iiop.openjdk.csiv2; import org.jboss.iiop.csiv2.SASCurrent; import org.omg.CORBA.LocalObject; import org.omg.IOP.Codec; import org.omg.IOP.ENCODING_CDR_ENCAPS; import org.omg.IOP.Encoding; import org.omg.PortableInterceptor.ORBInitInfo; import org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidName; import org.omg.PortableInterceptor.ORBInitializer; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * This is an {@link ORBInitializer} that initializes the Security Attibute Service (SAS) by installing an Elytron-based * client side interceptor and a SAS target interceptor that is used to populate the {@link SASCurrent} object. * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ @SuppressWarnings("unused") public class ElytronSASInitializer extends LocalObject implements ORBInitializer { @Override public void pre_init(ORBInitInfo info) { try { // create and register the SASCurrent. SASCurrent sasCurrent = new SASCurrentImpl(); info.register_initial_reference("SASCurrent", sasCurrent); // the SASCurrent still needs to be initialized. Its initialization is deferred to post_init, as it needs // to call resolve_initial_references. } catch (InvalidName e) { throw IIOPLogger.ROOT_LOGGER.errorRegisteringSASCurrentInitRef(e); } } @Override public void post_init(ORBInitInfo info) { try { org.omg.CORBA.Object obj; // Use CDR encapsulations with GIOP 1.0 encoding. Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte) 1, /* GIOP version */ (byte) 0 /* GIOP revision*/); Codec codec = info.codec_factory().create_codec(encoding); // Create and register client interceptor. obj = info.resolve_initial_references("SASCurrent"); SASCurrentImpl sasCurrentImpl = (SASCurrentImpl) obj; ElytronSASClientInterceptor clientInterceptor = new ElytronSASClientInterceptor(codec); info.add_client_request_interceptor(clientInterceptor); // Create and register server interceptor. SASTargetInterceptor serverInterceptor = new SASTargetInterceptor(codec); info.add_server_request_interceptor(serverInterceptor); // Initialize the SASCurrent implementation. sasCurrentImpl.init(serverInterceptor); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } }
3,208
39.620253
120
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIV2IORToSocketInfo.java
/* * Copyright (c) 2004,2016 Red Hat, Inc.,. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Red Hat designates this * particular file as subject to the "Classpath" exception as provided * by Red Hat in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.wildfly.iiop.openjdk.csiv2; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.omg.CSIIOP.CompoundSecMech; import org.omg.CSIIOP.CompoundSecMechList; import org.omg.CSIIOP.CompoundSecMechListHelper; import org.omg.CSIIOP.Confidentiality; import org.omg.CSIIOP.DetectMisordering; import org.omg.CSIIOP.DetectReplay; import org.omg.CSIIOP.EstablishTrustInClient; import org.omg.CSIIOP.EstablishTrustInTarget; import org.omg.CSIIOP.Integrity; import org.omg.CSIIOP.TAG_TLS_SEC_TRANS; import org.omg.CSIIOP.TLS_SEC_TRANS; import org.omg.CSIIOP.TLS_SEC_TRANSHelper; import org.omg.CSIIOP.TransportAddress; import org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS; import org.omg.IOP.TAG_CSI_SEC_MECH_LIST; import org.omg.IOP.TaggedComponent; import org.omg.SSLIOP.SSL; import org.omg.SSLIOP.SSLHelper; import org.omg.SSLIOP.TAG_SSL_SEC_TRANS; import org.wildfly.iiop.openjdk.Constants; import com.sun.corba.se.impl.encoding.CDRInputStream; import com.sun.corba.se.impl.encoding.EncapsInputStream; import com.sun.corba.se.spi.ior.IOR; import com.sun.corba.se.spi.ior.iiop.AlternateIIOPAddressComponent; import com.sun.corba.se.spi.ior.iiop.IIOPAddress; import com.sun.corba.se.spi.ior.iiop.IIOPProfileTemplate; import com.sun.corba.se.spi.orb.ORB; import com.sun.corba.se.spi.transport.IORToSocketInfo; import com.sun.corba.se.spi.transport.SocketInfo; import org.wildfly.iiop.openjdk.logging.IIOPLogger; import static java.security.AccessController.doPrivileged; /** * <p> * Implements an {@code com.sun.corba.se.spi.transport.IORToSocketInfo} which creates SocketInfo based on IOR contents. If CSIv2 * tagged component is present and it contains {@code org.omg.CSIIOP.TLS_SEC_TRANS} security mechanism then SSL socket is * created. * </p> * * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a> */ public class CSIV2IORToSocketInfo implements IORToSocketInfo { private static boolean clientRequiresSsl; public static void setClientRequiresSSL(final boolean clientRequiresSSL) { CSIV2IORToSocketInfo.clientRequiresSsl = clientRequiresSSL; } public List getSocketInfo(IOR ior) { List result = new ArrayList(); IIOPProfileTemplate iiopProfileTemplate = (IIOPProfileTemplate) ior.getProfile().getTaggedProfileTemplate(); IIOPAddress primary = iiopProfileTemplate.getPrimaryAddress(); String hostname = primary.getHost().toLowerCase(Locale.ENGLISH); int primaryPort = primary.getPort(); // NOTE: we could check for 0 (i.e., CSIv2) but, for a // non-CSIv2-configured client ORB talking to a CSIv2 configured // server ORB you might end up with an empty contact info list // which would then report a failure which would not be as // instructive as leaving a ContactInfo with a 0 port in the list. SocketInfo socketInfo; TransportAddress sslAddress = selectSSLTransportAddress(ior); SSL ssl = getSSL(ior); if (sslAddress != null) { socketInfo = createSSLSocketInfo(hostname, sslAddress.port); } else if (ssl != null) { socketInfo = createSSLSocketInfo(hostname, ssl.port); } else { // FIXME not all corba object export ssl port // if (clientRequiresSsl) { // throw new RuntimeException("Client requires SSL but target does not support it"); // } socketInfo = createSocketInfo(hostname, primaryPort); } result.add(socketInfo); addAlternateSocketInfos(iiopProfileTemplate, result); return result; } private SSL getSSL(IOR ior){ Iterator iter = ior.getProfile().getTaggedProfileTemplate().iteratorById(TAG_SSL_SEC_TRANS.value); if(!iter.hasNext()){ return null; } ORB orb = ior.getORB(); TaggedComponent compList = ((com.sun.corba.se.spi.ior.TaggedComponent) iter.next()).getIOPComponent(orb); CDRInputStream in = doPrivileged(new PrivilegedAction<CDRInputStream>() { @Override public CDRInputStream run() { return new EncapsInputStream(orb, compList.component_data, compList.component_data.length); } }); in.consumeEndian(); SSL ssl = SSLHelper.read(in); boolean targetRequiresSsl = ssl.target_requires > 0; boolean targetSupportsSsl = ssl.target_supports >0; if(!targetSupportsSsl && clientRequiresSsl){ throw IIOPLogger.ROOT_LOGGER.serverDoesNotSupportSsl(); } return targetSupportsSsl && (targetRequiresSsl || clientRequiresSsl) ? ssl : null; } private TransportAddress selectSSLTransportAddress(IOR ior) { CompoundSecMechList compoundSecMechList = readCompoundSecMechList(ior); if (compoundSecMechList != null) { for (CompoundSecMech mech : compoundSecMechList.mechanism_list) { TLS_SEC_TRANS sslMech = extractTlsSecTrans(ior, mech); if (sslMech == null) { continue; } boolean targetSupportsSsl = checkSSL(sslMech.target_supports); boolean targetRequiresSsl = checkSSL(sslMech.target_requires); if(!targetSupportsSsl && clientRequiresSsl){ throw IIOPLogger.ROOT_LOGGER.serverDoesNotSupportSsl(); } if (targetSupportsSsl && (targetRequiresSsl || clientRequiresSsl)) { return extractAddress(sslMech); } } } return null; } private boolean checkSSL(int options) { return (options & (Integrity.value | Confidentiality.value | DetectReplay.value | DetectMisordering.value | EstablishTrustInTarget.value | EstablishTrustInClient.value)) != 0; } private CompoundSecMechList readCompoundSecMechList(IOR ior) { Iterator iter = ior.getProfile().getTaggedProfileTemplate().iteratorById(TAG_CSI_SEC_MECH_LIST.value); if (!iter.hasNext()) { return null; } ORB orb = ior.getORB(); TaggedComponent compList = ((com.sun.corba.se.spi.ior.TaggedComponent) iter.next()).getIOPComponent(orb); CDRInputStream in = doPrivileged(new PrivilegedAction<CDRInputStream>() { @Override public CDRInputStream run() { return new EncapsInputStream(orb, compList.component_data, compList.component_data.length); } }); in.consumeEndian(); return CompoundSecMechListHelper.read(in); } private TLS_SEC_TRANS extractTlsSecTrans(IOR ior, CompoundSecMech mech) { TaggedComponent comp = mech.transport_mech; if (comp.tag != TAG_TLS_SEC_TRANS.value) { return null; } ORB orb = ior.getORB(); CDRInputStream in = doPrivileged(new PrivilegedAction<CDRInputStream>() { @Override public CDRInputStream run() { return new EncapsInputStream(orb, comp.component_data, comp.component_data.length); } }); in.consumeEndian(); return TLS_SEC_TRANSHelper.read(in); } private TransportAddress extractAddress(TLS_SEC_TRANS sslMech) { if (sslMech.addresses.length == 0) { return null; } return sslMech.addresses[0]; } private void addAlternateSocketInfos(IIOPProfileTemplate iiopProfileTemplate, final List result) { Iterator iterator = iiopProfileTemplate.iteratorById(TAG_ALTERNATE_IIOP_ADDRESS.value); while (iterator.hasNext()) { AlternateIIOPAddressComponent alternate = (AlternateIIOPAddressComponent) iterator.next(); String hostname = alternate.getAddress().getHost().toLowerCase(); int port = alternate.getAddress().getPort(); SocketInfo socketInfo = createSocketInfo(hostname, port); result.add(socketInfo); } } private SocketInfo createSocketInfo(final String hostname, final int port) { return new SocketInfo() { public String getType() { return SocketInfo.IIOP_CLEAR_TEXT; } public String getHost() { return hostname; } public int getPort() { return port; } }; } private SocketInfo createSSLSocketInfo(final String hostname, final int port) { return new SocketInfo() { public String getType() { return Constants.SSL_SOCKET_TYPE; } public String getHost() { return hostname; } public int getPort() { return port; } }; } }
9,925
38.545817
128
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIv2Initializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.omg.CORBA.LocalObject; import org.omg.IOP.Codec; import org.omg.IOP.ENCODING_CDR_ENCAPS; import org.omg.IOP.Encoding; import org.omg.PortableInterceptor.ORBInitInfo; import org.omg.PortableInterceptor.ORBInitializer; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * <p> * This class implements an {@code org.omg.PortableInterceptor.ORBinitializer} that installs a {@code CSIv2IORInterceptor} * and a {@code CSIv2PolicyFactory}. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ @SuppressWarnings("unused") public class CSIv2Initializer extends LocalObject implements ORBInitializer { @Override public void pre_init(ORBInitInfo info) { } @Override public void post_init(ORBInitInfo info) { try { // use CDR encapsulation with GIOP 1.0 encoding. Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte) 1, /* GIOP version */ (byte) 0 /* GIOP revision*/); Codec codec = info.codec_factory().create_codec(encoding); // add IOR interceptor for CSIv2. info.add_ior_interceptor(new CSIv2IORInterceptor(codec)); // register CSIv2-related policy factories. info.register_policy_factory(CSIv2Policy.TYPE, new CSIv2PolicyFactory(codec)); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } }
2,605
37.323529
122
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/csiv2/CSIv2PolicyFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.csiv2; import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData; import org.omg.CORBA.Any; import org.omg.CORBA.LocalObject; import org.omg.CORBA.Policy; import org.omg.CORBA.PolicyError; import org.omg.IOP.Codec; import org.omg.PortableInterceptor.PolicyFactory; /** * <p> * This class implements a {@code org.omg.PortableInterceptor.PolicyFactory} that creates {@code CSIv2Policy} policies. * </p> * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ class CSIv2PolicyFactory extends LocalObject implements PolicyFactory { private Codec codec; /** * <p> * Creates an instance of {@code CSIv2PolicyFactory} with the specified codec. * </p> * * @param codec the {@code Codec} used to encode the CSIv2 policies. */ public CSIv2PolicyFactory(Codec codec) { this.codec = codec; } @Override public Policy create_policy(int type, Any value) throws PolicyError { if (type != CSIv2Policy.TYPE) { throw new PolicyError(); } // stored as java.io.Serializable - is this a hack? IORSecurityConfigMetaData metadata = (IORSecurityConfigMetaData) value.extract_Value(); return new CSIv2Policy(metadata, codec); } }
2,382
34.567164
119
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/tm/ForeignTransaction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.tm; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import javax.transaction.xa.XAResource; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * A ForeignTransaction, a marker for when we would have to import a * transaction from another vendor. Which we don't do at the moment. * * @author <a href="adrian@jboss.com">Adrian Brock</a> */ public class ForeignTransaction implements Transaction { public static final ForeignTransaction INSTANCE = new ForeignTransaction(); private ForeignTransaction() { } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public void rollback() throws IllegalStateException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public void setRollbackOnly() throws IllegalStateException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public int getStatus() throws SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public boolean enlistResource(XAResource xaRes) throws RollbackException, IllegalStateException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } public void registerSynchronization(Synchronization sync) throws RollbackException, IllegalStateException, SystemException { throw IIOPLogger.ROOT_LOGGER.foreignTransaction(); } }
3,024
38.802632
118
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/tm/TxServerInterceptorInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.tm; import org.omg.CORBA.LocalObject; import org.omg.IOP.Codec; import org.omg.IOP.ENCODING_CDR_ENCAPS; import org.omg.IOP.Encoding; import org.omg.PortableInterceptor.ORBInitInfo; import org.omg.PortableInterceptor.ORBInitializer; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * This is an <code>org.omg.PortableInterceptor.ORBInitializer</code> that * installs a <code>TxServerInterceptor</code>. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> */ @SuppressWarnings("unused") public class TxServerInterceptorInitializer extends LocalObject implements ORBInitializer { static final long serialVersionUID = -547674655727747575L; public void pre_init(ORBInitInfo info) { } public void post_init(ORBInitInfo info) { try { // Use CDR encapsulation with GIOP 1.0 encoding Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte) 1, /* GIOP version */ (byte) 0 /* GIOP revision*/); Codec codec = info.codec_factory().create_codec(encoding); // Get a reference to the PICurrent org.omg.CORBA.Object obj = info.resolve_initial_references("PICurrent"); org.omg.PortableInterceptor.Current piCurrent = org.omg.PortableInterceptor.CurrentHelper.narrow(obj); // Initialize the fields slot id, codec, and piCurrent // in the interceptor class TxServerInterceptor.init(info.allocate_slot_id(), codec, piCurrent); // Create and register interceptor TxServerInterceptor interceptor = new TxServerInterceptor(); info.add_server_request_interceptor(interceptor); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } }
2,933
39.191781
91
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/tm/TxServerInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.tm; import jakarta.transaction.Transaction; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.LocalObject; import org.omg.CORBA.TCKind; import org.omg.CosTransactions.PropagationContextHelper; import org.omg.IOP.Codec; import org.omg.IOP.CodecPackage.FormatMismatch; import org.omg.IOP.CodecPackage.TypeMismatch; import org.omg.IOP.ServiceContext; import org.omg.PortableInterceptor.InvalidSlot; import org.omg.PortableInterceptor.ServerRequestInfo; import org.omg.PortableInterceptor.ServerRequestInterceptor; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * This implementation of * <code>org.omg.PortableInterceptor.ServerRequestInterceptor</code> * retrieves the transactional context from incoming IIOP requests and * makes it available to the servant methods that handle the requests, * through the static method <code>getCurrentTransaction</code). * * In practice this is only used to throw an exception when importing transactions from * a 3rd party application server, as required by the spec. * * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a> */ @SuppressWarnings("unused") public class TxServerInterceptor extends LocalObject implements ServerRequestInterceptor { static final long serialVersionUID = 7474707114565659371L; private static final int txContextId = org.omg.IOP.TransactionService.value; private static int slotId; private static Codec codec; private static org.omg.PortableInterceptor.Current piCurrent = null; /** * Called by <code>TxServerInterceptorInitializer</code> at ORB initialization time. */ static void init(int slotId, Codec codec, org.omg.PortableInterceptor.Current piCurrent) { TxServerInterceptor.slotId = slotId; TxServerInterceptor.codec = codec; TxServerInterceptor.piCurrent = piCurrent; } /** * Returns the transaction associated with the transaction propagation * context that arrived in the current IIOP request. */ public static Transaction getCurrentTransaction() { Transaction tx = null; if (piCurrent != null) { // A non-null piCurrent means that a TxServerInterceptor was // installed: check if there is a transaction propagation context try { Any any = piCurrent.get_slot(slotId); if (any.type().kind().value() != TCKind._tk_null) { // Yes, there is a TPC: add the foreign transaction marker tx = ForeignTransaction.INSTANCE; } } catch (InvalidSlot e) { throw IIOPLogger.ROOT_LOGGER.errorGettingSlotInTxInterceptor(e); } } return tx; } public String name() { return "TxServerInterceptor"; } public void destroy() { // do nothing } public void receive_request_service_contexts(ServerRequestInfo ri) { IIOPLogger.ROOT_LOGGER.tracef("Intercepting receive_request_service_contexts, operation: %s", ri.operation()); try { ServiceContext sc = ri.get_request_service_context(txContextId); Any any = codec.decode_value(sc.context_data, PropagationContextHelper.type()); ri.set_slot(slotId, any); } catch (BAD_PARAM e) { // no service context with txContextId: do nothing } catch (FormatMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorDecodingContextData(this.name(), e); } catch (TypeMismatch e) { throw IIOPLogger.ROOT_LOGGER.errorDecodingContextData(this.name(), e); } catch (InvalidSlot e) { throw IIOPLogger.ROOT_LOGGER.errorSettingSlotInTxInterceptor(e); } } public void receive_request(ServerRequestInfo ri) { // do nothing } public void send_reply(ServerRequestInfo ri) { // do nothing } public void send_exception(ServerRequestInfo ri) { // do nothing } public void send_other(ServerRequestInfo ri) { // do nothing } }
5,160
36.129496
118
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/tm/TxIORInterceptor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.tm; import org.omg.CORBA.Any; import org.omg.CORBA.LocalObject; import org.omg.CORBA.ORB; import org.omg.IOP.Codec; import org.omg.IOP.TaggedComponent; import org.omg.IOP.CodecPackage.InvalidTypeForEncoding; import org.omg.PortableInterceptor.IORInfo; import org.omg.PortableInterceptor.IORInterceptor; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Implements an <code>org.omg.PortableInterceptor.IORInterceptor</code> * that adds spec defined COSTransaction entries to an IOR. * * @author <a href="mailto:adrian@jboss.com">Adrian Brock</a> */ @SuppressWarnings("unused") public class TxIORInterceptor extends LocalObject implements IORInterceptor { /** * @since 4.0.1 */ static final long serialVersionUID = -1165643346307852265L; public static final int TAG_OTS_POLICY = 31; public static final int TAG_INV_POLICY = 32; public static final short EITHER = 0; public static final short ADAPTS = 3; private Codec codec; public TxIORInterceptor(Codec codec) { this.codec = codec; } public String name() { return TxIORInterceptor.class.getName(); } public void destroy() { } public void establish_components(IORInfo info) { try { // Invocation Policy = EITHER Any any = ORB.init().create_any(); any.insert_short(EITHER); byte[] taggedComponentData = codec.encode_value(any); info.add_ior_component(new TaggedComponent(TAG_INV_POLICY, taggedComponentData)); // OTS Policy = ADAPTS any = ORB.init().create_any(); any.insert_short(ADAPTS); taggedComponentData = codec.encode_value(any); info.add_ior_component(new TaggedComponent(TAG_OTS_POLICY, taggedComponentData)); } catch (InvalidTypeForEncoding e) { throw IIOPLogger.ROOT_LOGGER.errorEncodingContext(e); } } }
2,993
35.072289
93
java
null
wildfly-main/iiop-openjdk/src/main/java/org/wildfly/iiop/openjdk/tm/TxIORInterceptorInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.iiop.openjdk.tm; import org.omg.CORBA.LocalObject; import org.omg.IOP.Codec; import org.omg.IOP.ENCODING_CDR_ENCAPS; import org.omg.IOP.Encoding; import org.omg.PortableInterceptor.ORBInitInfo; import org.omg.PortableInterceptor.ORBInitializer; import org.wildfly.iiop.openjdk.logging.IIOPLogger; /** * Implements an <code>org.omg.PortableInterceptor.ORBinitializer</code> that * installs the <code>TxIORInterceptor</code> * * @author <a href="mailto:adrian@jboss.com">Adrian Brock</a> */ @SuppressWarnings("unused") public class TxIORInterceptorInitializer extends LocalObject implements ORBInitializer { /** * @since 4.0.1 */ static final long serialVersionUID = 963051265993070280L; public TxIORInterceptorInitializer() { // do nothing } public void pre_init(ORBInitInfo info) { // do nothing } public void post_init(ORBInitInfo info) { try { // Use CDR encapsulation with GIOP 1.0 encoding Encoding encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte) 1, /* GIOP version */ (byte) 0 /* GIOP revision*/); Codec codec = info.codec_factory().create_codec(encoding); info.add_ior_interceptor(new TxIORInterceptor(codec)); } catch (Exception e) { throw IIOPLogger.ROOT_LOGGER.unexpectedException(e); } } }
2,454
36.769231
88
java
null
wildfly-main/pojo/src/test/java/org/jboss/as/pojo/PojoSubsystemTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import java.io.IOException; import java.util.EnumSet; import java.util.Locale; import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> */ @RunWith(Parameterized.class) public class PojoSubsystemTestCase extends AbstractSubsystemBaseTest { @Parameters public static Iterable<PojoSubsystemSchema> parameters() { return EnumSet.allOf(PojoSubsystemSchema.class); } private final PojoSubsystemSchema schema; public PojoSubsystemTestCase(PojoSubsystemSchema schema) { super(PojoExtension.SUBSYSTEM_NAME, new PojoExtension()); this.schema = schema; } @Override protected String getSubsystemXml() throws IOException { return String.format(Locale.ROOT, "<subsystem xmlns=\"%s\" />", this.schema.getNamespace()); } @Override protected String getSubsystemXsdPath() throws Exception { return String.format(Locale.ROOT, "schema/jboss-as-pojo_%d_%d.xsd", this.schema.getVersion().major(), this.schema.getVersion().minor()); } }
2,240
36.35
144
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/PojoSubsystemSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import static org.jboss.as.controller.PersistentResourceXMLDescription.builder; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * Enumerates the supported namespaces of the POJO subsystem. * @author Paul Ferraro */ public enum PojoSubsystemSchema implements PersistentSubsystemSchema<PojoSubsystemSchema> { VERSION_1_0(1), ; static final PojoSubsystemSchema CURRENT = VERSION_1_0; private final VersionedNamespace<IntVersion, PojoSubsystemSchema> namespace; PojoSubsystemSchema(int major) { this.namespace = SubsystemSchema.createLegacySubsystemURN(PojoExtension.SUBSYSTEM_NAME, new IntVersion(major)); } @Override public VersionedNamespace<IntVersion, PojoSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return builder(PojoResource.PATH, this.namespace).build(); } }
2,207
36.423729
119
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/PojoSubsystemAdd.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.OperationContext; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.dmr.ModelNode; /** * Pojo subsystem add. * Define processors for POJO config handling. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> * @author Emanuel Muckenhuber */ class PojoSubsystemAdd extends AbstractBoottimeAddStepHandler { static final PojoSubsystemAdd INSTANCE = new PojoSubsystemAdd(); protected void populateModel(ModelNode operation, ModelNode model) { model.setEmptyObject(); } protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) { context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor(PojoExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_POJO_DEPLOYMENT, new KernelDeploymentParsingProcessor()); processorTarget.addDeploymentProcessor(PojoExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.POST_MODULE_POJO, new KernelDeploymentModuleProcessor()); processorTarget.addDeploymentProcessor(PojoExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_POJO_DEPLOYMENT, new ParsedKernelDeploymentProcessor()); } }, OperationContext.Stage.RUNTIME); } }
2,590
43.672414
170
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/KernelDeploymentModuleProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import org.jboss.as.pojo.descriptor.BaseBeanFactory; import org.jboss.as.pojo.descriptor.KernelDeploymentXmlDescriptor; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ModuleDependency; import org.jboss.as.server.deployment.module.ModuleSpecification; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; import org.jboss.modules.filter.PathFilter; import org.jboss.modules.filter.PathFilters; import java.util.List; /** * Check if we have any bean factories, as we need the POJO module api. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class KernelDeploymentModuleProcessor implements DeploymentUnitProcessor { private ModuleIdentifier POJO_MODULE = ModuleIdentifier.create("org.jboss.as.pojo"); /** * Add POJO module if we have any bean factories. * * @param phaseContext the deployment unit context * @throws org.jboss.as.server.deployment.DeploymentUnitProcessingException */ @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); final List<KernelDeploymentXmlDescriptor> kdXmlDescriptors = unit.getAttachment(KernelDeploymentXmlDescriptor.ATTACHMENT_KEY); if (kdXmlDescriptors == null || kdXmlDescriptors.isEmpty()) return; for (KernelDeploymentXmlDescriptor kdxd : kdXmlDescriptors) { if (kdxd.getBeanFactoriesCount() > 0) { final ModuleSpecification moduleSpecification = unit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); ModuleDependency dependency = new ModuleDependency(moduleLoader, POJO_MODULE, false, false, false, false); PathFilter filter = PathFilters.isChildOf(BaseBeanFactory.class.getPackage().getName()); dependency.addImportFilter(filter, true); dependency.addImportFilter(PathFilters.rejectAll(), false); moduleSpecification.addSystemDependency(dependency); return; } } } }
3,594
45.089744
134
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/BeanState.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; /** * A MC bean state. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public enum BeanState { NOT_INSTALLED, DESCRIBED, INSTANTIATED, CONFIGURED, CREATE, START, INSTALLED; /** * Get the next state. * * @return the next state */ public BeanState next() { return values()[ordinal() + 1]; } /** * Is this instance before state @param. * * @param state the state to check * @return true if before, false otherwise */ public boolean isBefore(BeanState state) { return state.ordinal() > ordinal(); } /** * Is this instance after state @param. * * @param state the state to check * @return true if after, false otherwise */ public boolean isAfter(BeanState state) { return state.ordinal() < ordinal(); } }
2,009
28.130435
70
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/ParseResult.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; /** * The result of a parsing operation. * * @param <T> the parse result type * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ParseResult<T> { private T result; /** * Set the result. * * @param result the parsing result */ public void setResult(T result) { this.result = result; } /** * Get the result. * * @return the parsing result */ public T getResult() { return result; } }
1,569
28.074074
70
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/PojoResource.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; /** * @author Tomaz Cerar * @created 7.2.12 14:41 */ public class PojoResource extends SimpleResourceDefinition { static final PathElement PATH = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, PojoExtension.SUBSYSTEM_NAME); PojoResource() { super(PATH, PojoExtension.SUBSYSTEM_RESOLVER, PojoSubsystemAdd.INSTANCE, ReloadRequiredRemoveStepHandler.INSTANCE); } }
1,688
40.195122
127
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/KernelDeploymentParsingProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.jboss.as.controller.xml.XMLElementSchema; import org.jboss.as.pojo.descriptor.BeanDeploymentSchema; import org.jboss.as.pojo.descriptor.KernelDeploymentXmlDescriptor; import org.jboss.as.pojo.logging.PojoLogger; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.staxmapper.XMLMapper; import org.jboss.vfs.VFSUtils; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VirtualFileFilter; import org.jboss.vfs.util.SuffixMatchFilter; /** * DeploymentUnitProcessor responsible for parsing a jboss-beans.xml * descriptor and attaching the corresponding KernelDeploymentXmlDescriptor. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class KernelDeploymentParsingProcessor implements DeploymentUnitProcessor { private final XMLMapper xmlMapper = XMLElementSchema.createXMLMapper(EnumSet.allOf(BeanDeploymentSchema.class)); private final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); /** * Process a deployment for jboss-beans.xml files. * Will parse the xml file and attach a configuration discovered during processing. * * @param phaseContext the deployment unit context * @throws DeploymentUnitProcessingException * */ @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit unit = phaseContext.getDeploymentUnit(); final VirtualFile deploymentRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); parseDescriptors(unit, deploymentRoot); final List<ResourceRoot> resourceRoots = unit.getAttachmentList(Attachments.RESOURCE_ROOTS); for (ResourceRoot root : resourceRoots) parseDescriptors(unit, root.getRoot()); } /** * Find and parse -jboss-beans.xml files. * * @param unit the deployment unit * @param root the root * @throws DeploymentUnitProcessingException * for any error */ protected void parseDescriptors(DeploymentUnit unit, VirtualFile root) throws DeploymentUnitProcessingException { if (root == null || root.exists() == false) return; Collection<VirtualFile> beans; final String name = root.getName(); if (name.endsWith("jboss-beans.xml")) { beans = Collections.singleton(root); } else { VirtualFileFilter filter = new SuffixMatchFilter("jboss-beans.xml"); beans = new ArrayList<VirtualFile>(); try { // try plain .jar/META-INF VirtualFile metainf = root.getChild("META-INF"); if (metainf.exists()) beans.addAll(metainf.getChildren(filter)); // allow for WEB-INF/*-jboss-beans.xml VirtualFile webinf = root.getChild("WEB-INF"); if (webinf.exists()) { beans.addAll(webinf.getChildren(filter)); // allow WEB-INF/classes/META-INF metainf = webinf.getChild("classes/META-INF"); if (metainf.exists()) beans.addAll(metainf.getChildren(filter)); } } catch (IOException e) { throw new DeploymentUnitProcessingException(e); } } for (VirtualFile beansXmlFile : beans) parseDescriptor(unit, beansXmlFile); } /** * Parse -jboss-beans.xml file. * * @param unit the deployment unit * @param beansXmlFile the beans xml file * @throws DeploymentUnitProcessingException * for any error */ protected void parseDescriptor(DeploymentUnit unit, VirtualFile beansXmlFile) throws DeploymentUnitProcessingException { if (beansXmlFile == null || beansXmlFile.exists() == false) return; InputStream xmlStream = null; try { xmlStream = beansXmlFile.openStream(); final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlStream); final ParseResult<KernelDeploymentXmlDescriptor> result = new ParseResult<KernelDeploymentXmlDescriptor>(); xmlMapper.parseDocument(result, reader); final KernelDeploymentXmlDescriptor xmlDescriptor = result.getResult(); if (xmlDescriptor != null) unit.addToAttachmentList(KernelDeploymentXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor); else throw PojoLogger.ROOT_LOGGER.failedToParse(beansXmlFile); } catch (DeploymentUnitProcessingException e) { throw e; } catch (Exception e) { throw PojoLogger.ROOT_LOGGER.parsingException(beansXmlFile, e); } finally { VFSUtils.safeClose(xmlStream); } } }
6,486
40.583333
124
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/PojoExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import java.util.EnumSet; import java.util.List; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.ParentResourceDescriptionResolver; import org.jboss.as.controller.descriptions.SubsystemResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * POJO extension. * Support JBoss5 and JBoss6 pojo configuration model. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> * @author Emanuel Muckenhuber */ public class PojoExtension implements Extension { public static final String SUBSYSTEM_NAME = "pojo"; static final ParentResourceDescriptionResolver SUBSYSTEM_RESOLVER = new SubsystemResourceDescriptionResolver(SUBSYSTEM_NAME, PojoExtension.class); private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0); private final PersistentResourceXMLDescription currentDescription = PojoSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new PojoResource()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE); subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); } @Override public void initializeParsers(ExtensionParsingContext context) { for (PojoSubsystemSchema schema : EnumSet.allOf(PojoSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == PojoSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } }
3,626
46.723684
174
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/ParsedKernelDeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo; import org.jboss.as.pojo.descriptor.BeanMetaDataConfig; import org.jboss.as.pojo.descriptor.ConfigVisitor; import org.jboss.as.pojo.descriptor.DefaultConfigVisitor; import org.jboss.as.pojo.descriptor.KernelDeploymentXmlDescriptor; import org.jboss.as.pojo.logging.PojoLogger; import org.jboss.as.pojo.service.DescribedPojoPhase; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceTarget; import java.util.List; /** * DeploymentUnit processor responsible for taking KernelDeploymentXmlDescriptor * configuration and creating the corresponding services. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class ParsedKernelDeploymentProcessor implements DeploymentUnitProcessor { /** * Process a deployment for KernelDeployment configuration. * Will install a {@code POJO} for each configured bean. * * @param phaseContext the deployment unit context * @throws DeploymentUnitProcessingException * */ public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); final List<KernelDeploymentXmlDescriptor> kdXmlDescriptors = unit.getAttachment(KernelDeploymentXmlDescriptor.ATTACHMENT_KEY); if (kdXmlDescriptors == null || kdXmlDescriptors.isEmpty()) return; final Module module = unit.getAttachment(Attachments.MODULE); if (module == null) throw PojoLogger.ROOT_LOGGER.noModuleFound(unit); final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); final DeploymentReflectionIndex index = unit.getAttachment(Attachments.REFLECTION_INDEX); if (index == null) throw PojoLogger.ROOT_LOGGER.missingReflectionIndex(unit); for (KernelDeploymentXmlDescriptor kdXmlDescriptor : kdXmlDescriptors) { final List<BeanMetaDataConfig> beanConfigs = kdXmlDescriptor.getBeans(); for (final BeanMetaDataConfig beanConfig : beanConfigs) { describeBean(module, serviceTarget, index, beanConfig); } // TODO -- KD::classloader, KD::aliases } } protected void describeBean(final Module module, final ServiceTarget serviceTarget, DeploymentReflectionIndex deploymentIndex, BeanMetaDataConfig beanConfig) { final BeanState state = BeanState.NOT_INSTALLED; final ServiceName describedServiceName = BeanMetaDataConfig.toBeanName(beanConfig.getName(), state.next()); final DescribedPojoPhase describedService = new DescribedPojoPhase(deploymentIndex, beanConfig); final ServiceBuilder describedServiceBuilder = serviceTarget.addService(describedServiceName, describedService); describedService.registerAliases(describedServiceBuilder); final ConfigVisitor visitor = new DefaultConfigVisitor(describedServiceBuilder, state, module, deploymentIndex); beanConfig.visit(visitor); describedServiceBuilder.setInitialMode(beanConfig.getMode().getMode()); describedServiceBuilder.install(); } }
4,644
47.894737
163
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/AbstractPojoPhase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo.service; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.jboss.as.pojo.BeanState; import org.jboss.as.pojo.logging.PojoLogger; import org.jboss.as.pojo.descriptor.BeanMetaDataConfig; import org.jboss.as.pojo.descriptor.CallbackConfig; import org.jboss.as.pojo.descriptor.ConfigVisitor; import org.jboss.as.pojo.descriptor.DefaultConfigVisitor; import org.jboss.as.pojo.descriptor.InstallConfig; import org.jboss.as.pojo.descriptor.ValueConfig; import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex; import org.jboss.modules.Module; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.Value; import org.wildfly.security.manager.WildFlySecurityManager; /** * Abstract pojo phase; it handles install/uninstall * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public abstract class AbstractPojoPhase implements Service<Object> { private Module module; private BeanMetaDataConfig beanConfig; private DeploymentReflectionIndex index; private BeanInfo beanInfo; private Object bean; protected abstract BeanState getLifecycleState(); protected abstract AbstractPojoPhase createNextPhase(); public void start(StartContext context) throws StartException { if (module != null) { final ClassLoader previous = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader()); try { startInternal(context); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(previous); } } else { startInternal(context); } } protected void startInternal(StartContext context) throws StartException { try { executeInstalls(); // only after describe do we have a bean if (getLifecycleState().isAfter(BeanState.DESCRIBED)) { addCallbacks(true); addCallbacks(false); ServiceRegistry registry = context.getController().getServiceContainer(); InstancesService.addInstance(registry, context.getChildTarget(), getLifecycleState(), getBean()); } final AbstractPojoPhase nextPhase = createNextPhase(); // do we have a next phase if (nextPhase != null) { final BeanState state = getLifecycleState(); final BeanState next = state.next(); final BeanMetaDataConfig beanConfig = getBeanConfig(); final ServiceName name = BeanMetaDataConfig.toBeanName(beanConfig.getName(), next); final ServiceTarget serviceTarget = context.getChildTarget(); final ServiceBuilder serviceBuilder = serviceTarget.addService(name, nextPhase); registerAliases(serviceBuilder, next); final ConfigVisitor visitor = new DefaultConfigVisitor(serviceBuilder, state, getModule(), getIndex(), getBeanInfo()); beanConfig.visit(visitor); nextPhase.setModule(getModule()); nextPhase.setBeanConfig(getBeanConfig()); nextPhase.setIndex(getIndex()); nextPhase.setBeanInfo(getBeanInfo()); nextPhase.setBean(getBean()); serviceBuilder.install(); } } catch (Throwable t) { throw new StartException(t); } } protected void registerAliases(ServiceBuilder serviceBuilder, BeanState next) { final Set<String> aliases = beanConfig.getAliases(); if (aliases != null) { for (String alias : aliases) { ServiceName asn = BeanMetaDataConfig.toBeanName(alias, next); serviceBuilder.addAliases(asn); } } } @Override public Object getValue() throws IllegalStateException, IllegalArgumentException { return getBean(); } public void stop(StopContext context) { if (module != null) { final ClassLoader previous = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader()); try { stopInternal(context); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(previous); } } else { stopInternal(context); } } protected void stopInternal(StopContext context) { if (getLifecycleState().isAfter(BeanState.DESCRIBED)) { InstancesService.removeInstance(context.getController().getServiceContainer(), getLifecycleState(), getBean()); removeCallbacks(true); removeCallbacks(false); } executeUninstalls(); } private List<Joinpoint> getInstalls() { List<InstallConfig> installs = getBeanConfig().getInstalls(); return (installs != null) ? toJoinpoints(installs) : Collections.<Joinpoint>emptyList(); } private List<Joinpoint> getUninstalls() { List<InstallConfig> uninstalls = getBeanConfig().getUninstalls(); return (uninstalls != null) ? toJoinpoints(uninstalls) : Collections.<Joinpoint>emptyList(); } private List<Joinpoint> toJoinpoints(List<InstallConfig> installs) { List<Joinpoint> joinpoints = new ArrayList<Joinpoint>(); for (InstallConfig ic : installs) { if (ic.getWhenRequired() == getLifecycleState()) joinpoints.add(createJoinpoint(ic)); } return joinpoints; } protected Joinpoint createJoinpoint(InstallConfig config) { String methodName = config.getMethodName(); if (methodName == null) throw PojoLogger.ROOT_LOGGER.nullMethodName(); ValueConfig[] parameters = config.getParameters(); String[] types = Configurator.getTypes(parameters); String dependency = config.getDependency(); Value<Object> target = (dependency != null) ? config.getBean() : () -> getBean(); BeanInfo beanInfo = (dependency != null) ? config.getBeanInfo().getValue() : getBeanInfo(); Method method = beanInfo.findMethod(methodName, types); MethodJoinpoint joinpoint = new MethodJoinpoint(method); joinpoint.setTarget(target); joinpoint.setParameters(parameters); return joinpoint; } protected void executeInstalls() throws StartException { List<Joinpoint> installs = getInstalls(); if (installs.isEmpty()) return; int i = 0; try { for (i = 0; i < installs.size(); i++) installs.get(i).dispatch(); } catch (Throwable t) { considerUninstalls(getUninstalls(), i); throw new StartException(t); } } /** * Consider the uninstalls. * <p/> * This method is here to be able to override * the behavior after installs failed. * e.g. perhaps only running uninstalls from the index. * <p/> * By default we run all uninstalls in the case * at least one install failed. * * @param uninstalls the uninstalls * @param index current installs index */ protected void considerUninstalls(List<Joinpoint> uninstalls, int index) { if (uninstalls == null) return; for (int j = Math.min(index, uninstalls.size() - 1); j >= 0; j--) { try { uninstalls.get(j).dispatch(); } catch (Throwable t) { PojoLogger.ROOT_LOGGER.ignoreUninstallError(uninstalls.get(j), t); } } } protected void executeUninstalls() { considerUninstalls(getUninstalls(), Integer.MAX_VALUE); } protected void addCallbacks(boolean install) { List<CallbackConfig> configs = (install ? getBeanConfig().getIncallbacks() : getBeanConfig().getUncallbacks()); if (configs != null) { for (CallbackConfig cc : configs) { if (cc.getWhenRequired() == getLifecycleState()) { Callback callback = new Callback(getBeanInfo(), getBean(), cc); if (install) InstancesService.addIncallback(callback); else InstancesService.addUncallback(callback); } } } } protected void removeCallbacks(boolean install) { List<CallbackConfig> configs = (install ? getBeanConfig().getIncallbacks() : getBeanConfig().getUncallbacks()); if (configs != null) { for (CallbackConfig cc : configs) { if (cc.getWhenRequired() == getLifecycleState()) { Callback callback = new Callback(getBeanInfo(), getBean(), cc); if (install) InstancesService.removeIncallback(callback); else InstancesService.removeUncallback(callback); } } } } protected Module getModule() { return module; } protected void setModule(Module module) { this.module = module; } protected BeanMetaDataConfig getBeanConfig() { return beanConfig; } protected DeploymentReflectionIndex getIndex() { return index; } protected void setBeanConfig(BeanMetaDataConfig beanConfig) { this.beanConfig = beanConfig; } protected void setIndex(DeploymentReflectionIndex index) { this.index = index; } protected BeanInfo getBeanInfo() { return beanInfo; } protected void setBeanInfo(BeanInfo beanInfo) { this.beanInfo = beanInfo; } protected Object getBean() { return bean; } protected void setBean(Object bean) { this.bean = bean; } }
11,444
36.038835
134
java
null
wildfly-main/pojo/src/main/java/org/jboss/as/pojo/service/BeanInfo.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.pojo.service; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Bean info API. * It checks the whole bean's class hierarchy. * * @param <T> the exact bean type * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public interface BeanInfo<T> { /** * Get ctor; exact match wrt parameter types. * * @param parameterTypes the parameter types * @return the found ctor */ Constructor<T> getConstructor(String... parameterTypes); /** * Find ctor. * Loose parameter type matching; not all types need to be known. * * @param parameterTypes the parameter types * @return the found ctor */ Constructor<T> findConstructor(String... parameterTypes); /** * Get method; exact match wrt parameter types. * * @param name the method name * @param parameterTypes the parameter types * @return found method */ Method getMethod(String name, String... parameterTypes); /** * Find method. * Loose parameter type matching; not all types need to be known. * * @param name the method name * @param parameterTypes the parameter types * @return found method */ Method findMethod(String name, String... parameterTypes); /** * Get getter. * * @param propertyName the getter propertyName * @param type the type propertyName * @return the found getter */ Method getGetter(String propertyName, Class<?> type); /** * Get setter. * * @param propertyName the setter propertyName * @param type the type propertyName * @return the found setter */ Method getSetter(String propertyName, Class<?> type); /** * Get bean's field. * * @param name the field name * @return the found field */ Field getField(String name); }
2,973
29.040404
70
java